<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace YMApi\Model;
use Think\Model;

class CartModel extends Model
{
    protected $tableName = 'cart';
    
    /*
     * 我的购物车
     * */
    
    public function my_shopping_cart($uid){
        /* 初始化 */
        $goods_list = array();
        $total = array(
            'goods_price' => 0, // 本店售价合计（有格式）
            'market_price' => 0, // 市场售价合计（有格式）
            'saving' => 0, // 节省金额（有格式）
            'save_rate' => 0, // 节省百分比
            'goods_amount' => 0, // 本店售价合计（无格式）
            'total_number' => 0,
        );
        /* 循环、统计 */
        $sql = "SELECT *, IF(parent_id, parent_id, goods_id) AS pid " .
            " FROM " . C('DB_PREFIX') . "cart " .
            " WHERE user_id='" . $uid . "' AND rec_type='" . CART_GENERAL_GOODS . "'" .
            " ORDER BY pid, parent_id";
        $res = $this->query($sql);
        /* 用于统计购物车中实体商品和虚拟商品的个数 */
        $virtual_goods_count = 0;
        $real_goods_count = 0;
        foreach ($res as $row) {
            $total['total_number']+=$row['goods_number'];
            $total['goods_price'] += $row['goods_price'] * $row['goods_number'];
            $total['market_price'] += $row['market_price'] * $row['goods_number'];
        
            $row['subtotal'] = price_format($row['goods_price'] * $row['goods_number'], false);
            $row['goods_price'] = price_format($row['goods_price'], false);
            $row['market_price'] = price_format($row['market_price'], false);
        
            /* 统计实体商品和虚拟商品的个数 */
            if ($row['is_real']) {
                $real_goods_count++;
            } else {
                $virtual_goods_count++;
            }
        
            /* 查询规格 */
            if (trim($row['goods_attr']) != '') {
                $row['goods_attr'] = addslashes($row['goods_attr']);
                $sql = "SELECT attr_value FROM " . C('DB_PREFIX') . "goods_attr WHERE goods_attr_id " .
                    db_create_in($row['goods_attr_id']);
                $attr_list = $this->query($sql);
                foreach ($attr_list as $attr) {
                    $row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
                }
            }
            /* 增加是否在购物车里显示商品图 */
            if ((C('show_goods_in_cart') == "2" || C('show_goods_in_cart') == "3") && $row['extension_code'] != 'package_buy') {
                $res = $this->row("SELECT `goods_thumb` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
                $goods_thumb = img_init($res['goods_thumb']);
                $row['goods_thumb'] = get_image_path($row['goods_id'], $goods_thumb, true);
            }
            if ($row['extension_code'] == 'package_buy') {
                $row['package_goods_list'] = model('PackageBase')->get_package_goods($row['goods_id']);
            }
            //获取库存
            $res = $this->row("SELECT `goods_number` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
            $row['goods_max_number'] = $res['goods_number'];
            $goods_list[] = $row;
        }
        $total['goods_amount'] = $total['goods_price'];
        $total['saving'] = price_format($total['market_price'] - $total['goods_price'], false);
        if ($total['market_price'] > 0) {
            $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
                100 / $total['market_price']) . '%' : 0;
        }
        $total['goods_price'] = price_format($total['goods_price'], false);
        $total['market_price'] = price_format($total['market_price'], false);
        $total['real_goods_count'] = $real_goods_count;
        $total['virtual_goods_count'] = $virtual_goods_count;
        
        return array('goods_list' => $goods_list, 'total' => $total);
    }
    
    
    /*
     * 添加购物车
     * */
    
    public function add_shoppingcart($uid,$goods_id,$num=1,$spec = array(), $parent = 0,$wid=0){
    	$user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        $_parent_id = $parent;
        /* 取得商品信息 */
        if(empty($_SESSION[discount]) || $_SESSION[discount]=='0.00'){
            $_SESSION[discount]=1;
        }
        $Model=new Model();
        if($wid){
            $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, " .
                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, " .
                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, " .
                "g.goods_number, g.is_alone_sale, g.is_shipping,is_presell," .
                " IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price " .
                " FROM " . C('DB_PREFIX') . "goods AS g " .
                " LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$user_rank' " .
                " LEFT JOIN " . C('DB_PREFIX') . "goods_storage AS gs " .
                "ON gs.goods_id = g.goods_id" .
                " WHERE g.goods_id = '$goods_id'" .
                " AND gs.wid=".$wid." AND g.is_delete = 0 limit 1";
        }else{
            $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, " .
                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, " .
                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, " .
                "g.goods_number, g.is_alone_sale, g.is_shipping,is_presell," .
                " IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price " .
                " FROM " . C('DB_PREFIX') . "goods AS g " .
                " LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$user_rank' " .
                " WHERE g.goods_id = '$goods_id'" .
                " AND g.is_delete = 0 limit 1";
        }
        $goods = $Model->query($sql);
        $goods=$goods[0];
        if (empty($goods)) {
            returnApiError('该商品不存在。');
        }

        /* 如果是作为配件添加到购物车的，需要先检查购物车里面是否已经有基本件 */
        if ($parent > 0) {
            $sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') .
                    "cart WHERE goods_id='$parent' AND user_id='" . $uid . "' AND extension_code <> 'package_buy' limit 1";
            $res = $Model->query($sql);
            if ($res[0]['count'] == 0) {
                returnApiError('该配件不在购物车中');
            }
        }
        /* 是否正在销售 */
        if ($goods['is_on_sale'] == 0) {
            returnApiError('商品已下架。');
        }
        
        /* 不是配件时检查是否允许单独销售 */
        if (empty($parent) && $goods['is_alone_sale'] == 0) {
            returnApiError('该商品不单独销售。');
        }

        
        /* 如果商品有规格则取规格商品信息 配件除外 */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
        $prod = $Model->query($sql);
        if (D('Goods')->is_spec($spec) && !empty($prod)) {
            $product_info = D('Goods')->get_products_info($goods_id, $spec);
        }
        if (empty($product_info)) {
            $product_info = array('product_number' => '', 'product_id' => 0);
        }

        /* 检查：库存 */
        if (C('use_storage') == 1) {
            //检查：商品购买数量是否大于总库存
            if($wid){
                if(!D('Goodsstorage')->check_warehous_goods($wid,$goods_id,$num)){
                   returnApiError('该商品不单独销售。');
                }
            }else{
                if ($num > $goods['goods_number']) {
                    returnApiError('该商品不单独销售。');
                }
            }
           
            //商品存在规格 是货品 检查该货品库存
            if (D('Goods')->is_spec($spec) && !empty($prod)) {
                if (!empty($spec)) {
                    /* 取规格的货品库存 */
                    if ($num > $product_info['product_number']) {
                       returnApiError('库存不足。');
                    }
                }
            }
        }

        /* 计算商品的促销价格 */
        $spec_price = D('Goods')->spec_price($spec);
        $goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
        $goods['market_price'] += $spec_price;
        $goods_attr = D('Goods')->get_goods_attr_info($spec);
        $goods_attr_id = join(',', $spec);

//        促销价
		$goods = D('goods')->get_goods_info_by_promote($goods_id);
		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
		if ($promote_price > 0) {
			$act_type = 4;
		}else{
			$act_type = 0;
		}


        /* 初始化要插入购物车的基本件数据 */
        $parent = array(
            'user_id' => $uid,
            'session_id' => SESS_ID,
            'goods_id' => $goods_id,
            'goods_sn' => addslashes($goods['goods_sn']),
            'product_id' => $product_info['product_id'],
            'goods_name' => addslashes($goods['goods_name']),
            'market_price' => $goods['market_price'],
            'goods_attr' => addslashes($goods_attr),
            //'goods_attr_id' => $goods_attr_id,
            'is_real' => $goods['is_real'],
            'extension_code' => $goods['extension_code'],
            'is_gift' => 0,
            'is_quota' => 0,
            'is_shipping' => $goods['is_shipping'],
            'is_presell'=>$goods['is_presell'],
            'rec_type' => CART_GENERAL_GOODS,
			'giving' =>	$act_type,
        );
        if(!empty($goods_attr_id)){
            $parent['goods_attr_id']=$goods_attr_id;
        }
        /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
        /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
        /* 受此优惠 */
        $basic_list = array();
        $sql = "SELECT parent_id, goods_price " .
                "FROM " . C('DB_PREFIX') .
                "group_goods WHERE goods_id = '$goods_id'" .
                " AND goods_price < '$goods_price'" .
                " AND parent_id = '$_parent_id'" .
                " ORDER BY goods_price";
        $res = $Model->query($sql);
        foreach ($res as $key=>$row) {
            $basic_list[$row['parent_id']] = $row['goods_price'];
        }
        /* 取得购物车中该商品每个基本件的数量 */
        $basic_count_list = array();
        
        if ($basic_list) {
            $sql = "SELECT goods_id, SUM(goods_number) AS count " .
                    "FROM " . C('DB_PREFIX') .
                    "cart WHERE user_id = '" . $uid . "'" .
                    " AND parent_id = 0" .
                    " AND extension_code <> 'package_buy' " .
                    " AND goods_id " . db_create_in(array_keys($basic_list)) .
                    " GROUP BY goods_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['goods_id']] = $row['count'];
            }
        }
        
        /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
        /* 一个基本件对应一个该商品配件 */
        if ($basic_count_list) {
            $sql = "SELECT parent_id, SUM(goods_number) AS count " .
                    "FROM " .C('DB_PREFIX') .
                    "cart WHERE user_id = '" . $uid . "'" .
                    " AND goods_id = '$goods_id'" .
                    " AND extension_code <> 'package_buy' " .
                    " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
                    " GROUP BY parent_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['parent_id']] -= $row['count'];
            }
        }

        /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
        foreach ($basic_list as $parent_id => $fitting_price) {
            /* 如果已全部插入，退出 */
            if ($num <= 0) {
                break;
            }

            /* 如果该基本件不再购物车中，执行下一个 */
            if (!isset($basic_count_list[$parent_id])) {
                continue;
            }

            /* 如果该基本件的配件数量已满，执行下一个基本件 */
            if ($basic_count_list[$parent_id] <= 0) {
                continue;
            }

            /* 作为该基本件的配件插入 */
            $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
            $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
            $parent['parent_id'] = $parent_id;

            /* 添加 */
            M('cart')->add($parent);
            /* 改变数量 */
            $num -= $parent['goods_number'];
        }
        
        /* 如果数量不为0，作为基本件插入 */
        if ($num > 0) {
            /* 检查该商品是否已经存在在购物车中 */
            $sql = "SELECT goods_number FROM " . C('DB_PREFIX') .
                    "cart WHERE user_id = '" . $uid . "' AND goods_id = '$goods_id' " .
                    " AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " .
                    " AND extension_code <> 'package_buy' " .
                    " AND is_quota=0" .
                    " AND rec_type = '" . CART_GENERAL_GOODS . "'";
            $row = $Model->query($sql);
            $row=$row[0];
            
            if ($row) { //如果购物车已经有此物品，则更新
                //$num += $row['goods_number'];
                if (D('Goods')->is_spec($spec) && !empty($prod)) {
                    $goods_storage = $product_info['product_number'];
                } else {
                    $goods_storage = $goods['goods_number'];
                }
                if ($num <= $goods_storage) {
                    $goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$goods_price
                    );
                    $where=array(
                        'user_id'=>$uid,
                        'goods_id'=>$goods_id,
                        'parent_id'=>0,
                        'goods_attr'=>D('Goods')->get_goods_attr_info($spec),
                        'extension_code'=>array('neq','package_buy'),
                        'is_quota'=>0,
                        'rec_type'=>CART_GENERAL_GOODS
                    );
                    $this->where($where)->save($cartdata);
                    /*$sql = "UPDATE " . C('DB_PREFIX') . "cart SET goods_number = '$num'" .
                            " , goods_price = '$goods_price'" .
                            " WHERE session_id = '" . SESS_ID . "' AND goods_id = '$goods_id' " .
                            " AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " .
                            " AND extension_code != 'package_buy' " .
                            " AND is_quota=0 " .
                            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
                    echo $sql;
                    exit;
                    $id=$Model->query($sql);*/
                } else {
                    returnApiError('库存不足');;
                }
            } else { //购物车没有此物品，则插入
                $goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
                $parent['goods_price'] = max($goods_price, 0);
                $parent['goods_number'] = $num;
                $parent['parent_id'] = 0;
                $this->add($parent);
            }
        }
        
        /* 把赠品删除 */
        $where=array(
            'user_id'=>$uid,
            'is_gift'=>array('neq',0),
        );
        M('Cart')->where($where)->delete();
       /* $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE session_id = '" . SESS_ID . "' AND is_gift != 0";
        $id=$Model->query($sql);*/
        return true;
    }
    
    /*
     * 增减购物车
     * */
    
    public function change_shoppingcart($uid,$goods_id,$num=1,$spec = array(), $parent = 0,$wid=0,$operate="add"){
    	$user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
    	$_parent_id = $parent;
    	/* 取得商品信息 */
    	if(empty($_SESSION[discount]) || $_SESSION[discount]=='0.00'){
    		$user_rank = D('Users')->get_user_rank($uid);
    		$_SESSION[discount]=$user_rank['discount'];
    	}
    	$Model=new Model();
    	
    	$sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, " .
    			"g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, " .
    			"g.promote_end_date, g.goods_weight, g.integral, g.extension_code, " .
    			"g.goods_number, g.is_alone_sale, g.is_shipping,g.is_presell," .
    			" IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price " .
    			" FROM " . C('DB_PREFIX') . "goods AS g " .
    			" LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
    			"ON mp.goods_id = g.goods_id AND mp.user_rank = '$user_rank' " .
    			" WHERE g.goods_id = '$goods_id'" .
    			" AND g.is_delete = 0 limit 1";
    	
    	$goods = $Model->query($sql);
    	$goods=$goods[0];
    	if (empty($goods)) {
    		returnApiError('商品不存在或已下架');
    	}
    	
    	//检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
//     	$goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid);
    
    	/* 如果是作为配件添加到购物车的，需要先检查购物车里面是否已经有基本件 */
    	if ($parent > 0) {
    		$sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') .
    		"cart WHERE goods_id='$parent' AND user_id='" . $uid . "' AND extension_code <> 'package_buy' limit 1";
    		$res = $Model->query($sql);
    		if ($res[0]['count'] == 0) {
    			returnApiError('该配件不在购物车中');
    		}
    	}
    	/* 是否正在销售 */
    	if ($goods['is_on_sale'] == 0) {
    		returnApiError('商品已下架');
    	}
    
    	/* 不是配件时检查是否允许单独销售 */
    	if (empty($parent) && $goods['is_alone_sale'] == 0) {
    		returnApiError('该商品不能单独销售');
    	}
    
    
    	/* 如果商品有规格则取规格商品信息 配件除外 */
    	$sql = "SELECT * FROM " . C('DB_PREFIX') . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
    	$prod = $Model->query($sql);
    	if (D('Goods')->is_spec($spec) && !empty($prod)) {
    		$product_info = D('Goods')->get_products_info($goods_id, $spec);
    	}
    	if (empty($product_info)) {
    		$product_info = array('product_number' => '', 'product_id' => 0);
    	}
    
    	/* 检查：库存 */
    	if (C('use_storage') == 1 && $operate=='add') {
    		//检查：商品购买数量是否大于总库存
    		//检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
    	     $goods['is_presell']=(int)$goods['is_presell'];
    	    if($goods['is_presell']!=0){
    	       $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods_id,$wid);
    		}
    		if($goods['is_presell']==1 || empty($wid)){
    			if ($num > $goods['goods_number']) {
    				returnApiError('库存不足');
    			}
    			//商品存在规格 是货品 检查该货品库存
    			if (D('Goods')->is_spec($spec) && !empty($prod)) {
    				if (!empty($spec)) {
    					/* 取规格的货品库存 */
    					if ($num > $product_info['product_number']) {
    						returnApiError('库存不足');
    					}
    				}
    			}
    		}elseif($wid){
    		    if(!D('Goodsstorage')->check_warehous_goods($wid,$goods_id,$num)){
    		        returnApiError('仓库库存不足');
    		    }
    		}
    	}
    
    	/* 计算商品的促销价格 */
    	$spec_price = D('Goods')->spec_price($spec);
    	$goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
    	$goods['market_price'] += $spec_price;
    	$goods_attr = D('Goods')->get_goods_attr_info($spec);
    	$goods_attr_id = join(',', $spec);

		$giving = 0;
		$goods = D('goods')->get_goods_info_by_promote($goods_id);
		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
		if ($promote_price > 0) {
			$giving = 4;
		}
    	
    	/* 初始化要插入购物车的基本件数据 */
		$parent = array(
			'user_id' => $uid,
			'session_id' => SESS_ID,
			'goods_id' => $goods_id,
			'goods_sn' => addslashes($goods['goods_sn']),
			'product_id' => $product_info['product_id'],
			'goods_name' => addslashes($goods['goods_name']),
			'market_price' => empty($goods['market_price']) ? 0 : trim($goods['market_price']),
			'goods_attr' => addslashes($goods_attr),
			//'goods_attr_id' => $goods_attr_id,
			'is_real' => empty($goods['is_real']) ? 0 : trim($goods['is_real']),
			'extension_code' => empty($goods['extension_code']) ? '' : trim($goods['extension_code']),
			'is_gift' => 0,
			'is_quota' => 0,
			'is_shipping' => empty($goods['is_shipping']) ? 0 : trim($goods['is_shipping']),
			'is_presell' => empty($goods['is_presell']) ? 0 : trim($goods['is_presell']),
			'rec_type' => CART_GENERAL_GOODS,
			'giving' => $giving,
		);

    	if(!empty($goods_attr_id)){
    		$parent['goods_attr_id']=$goods_attr_id;
    	}
    	if($operate=="add"){
    		//分类限购检查
    		$res = D('Goods')->check_cat_max_buy_number($parent,$goods_price,$uid,$num);
    	}
    	
    	/* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
    	/* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
    	/* 受此优惠 */
    	$basic_list = array();
    	$sql = "SELECT parent_id, goods_price " .
    			"FROM " . C('DB_PREFIX') .
    			"group_goods WHERE goods_id = '$goods_id'" .
    			" AND goods_price < '$goods_price'" .
    			" AND parent_id = '$_parent_id'" .
    			" ORDER BY goods_price";
    	$res = $Model->query($sql);
    	foreach ($res as $key=>$row) {
    		$basic_list[$row['parent_id']] = $row['goods_price'];
    	}
    	/* 取得购物车中该商品每个基本件的数量 */
    	$basic_count_list = array();
    
    	if ($basic_list) {
    		$sql = "SELECT goods_id, SUM(goods_number) AS count " .
    				"FROM " . C('DB_PREFIX') .
    				"cart WHERE user_id = '" . $uid . "'" .
    				" AND parent_id = 0" .
    				" AND extension_code <> 'package_buy' " .
    				" AND goods_id " . db_create_in(array_keys($basic_list)) .
    				" GROUP BY goods_id";
    		$res = $Model->query($sql);
    		foreach ($res as $key=>$row) {
    			$basic_count_list[$row['goods_id']] = $row['count'];
    		}
    	}
    
    	/* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
    	/* 一个基本件对应一个该商品配件 */
    	if ($basic_count_list) {
    		$sql = "SELECT parent_id, SUM(goods_number) AS count " .
    				"FROM " .C('DB_PREFIX') .
    				"cart WHERE user_id = '" . $uid . "'" .
    				" AND goods_id = '$goods_id'" .
    				" AND extension_code <> 'package_buy' " .
    				" AND parent_id " . db_create_in(array_keys($basic_count_list)) .
    				" GROUP BY parent_id";
    		$res = $Model->query($sql);
    		foreach ($res as $key=>$row) {
    			$basic_count_list[$row['parent_id']] -= $row['count'];
    		}
    	}
    
    	/* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
    	foreach ($basic_list as $parent_id => $fitting_price) {
    		/* 如果已全部插入，退出 */
    		if ($num <= 0) {
    			break;
    		}
    
    		/* 如果该基本件不再购物车中，执行下一个 */
    		if (!isset($basic_count_list[$parent_id])) {
    			continue;
    		}
    
    		/* 如果该基本件的配件数量已满，执行下一个基本件 */
    		if ($basic_count_list[$parent_id] <= 0) {
    			continue;
    		}
    
    		/* 作为该基本件的配件插入 */
    		$parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
    		$parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
    		$parent['parent_id'] = $parent_id;
    
    		/* 添加 */
    		M('cart')->add($parent);
    		/* 改变数量 */
    		$num -= $parent['goods_number'];
    	}
    
    	/* 如果数量不为0，作为基本件插入 */
    	if ($num > 0) {
    		/* 检查该商品是否已经存在在购物车中 */
    		$sql = "SELECT rec_id,goods_number FROM " . C('DB_PREFIX') .
    		"cart WHERE user_id = '" . $uid . "' AND goods_id = '$goods_id' " .
    		" AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " .
    		" AND extension_code <> 'package_buy' " .
    		" AND is_quota=0" .
    		" AND rec_type = '" . CART_GENERAL_GOODS . "'";
    		$row = $Model->query($sql);
    		$row=$row[0];
    
    		if ($row) { //如果购物车已经有此物品，则更新
    			//$num += $row['goods_number'];
    			$rec_id = $row['rec_id'];
    			if($goods['is_presell']==1 || empty($wid)){
    				if (D('Goods')->is_spec($spec) && !empty($prod)) {
    					$goods_storage = $product_info['product_number'];
    				} else {
    					$goods_storage = $goods['goods_number'];
    				}
    			}elseif($wid){
    				$goods_storage = D('Goodsstorage')->get_warehous_goods($wid,$goods_id);
    			}
    			
    			if ($num <= $goods_storage) {
    				$goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
    				$cartdata=array(
    						'goods_number'=>$num,
    						'goods_price'=>$goods_price
    				);
//     				$where=array(
//     						'user_id'=>$uid,
//     						'goods_id'=>$goods_id,
//     						'parent_id'=>0,
//     						'goods_attr'=>D('Goods')->get_goods_attr_info($spec),
//     						'extension_code'=>array('neq','package_buy'),
//     						'is_quota'=>0,
//     						'rec_type'=>CART_GENERAL_GOODS
//     				);
    				$where = array('rec_id'=>$rec_id,'user_id'=>$uid,'goods_id'=>$goods_id);
    				M('Cart')->where($where)->save($cartdata);
    				/*$sql = "UPDATE " . C('DB_PREFIX') . "cart SET goods_number = '$num'" .
    				 " , goods_price = '$goods_price'" .
    				 " WHERE session_id = '" . SESS_ID . "' AND goods_id = '$goods_id' " .
    				 " AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " .
    				 " AND extension_code != 'package_buy' " .
    				 " AND is_quota=0 " .
    				 "AND rec_type = '" . CART_GENERAL_GOODS . "'";
    				 echo $sql;
    				 exit;
    				$id=$Model->query($sql);*/
    			}elseif($goods['is_presell']) {
    				returnApiError('库存不足');
    			}elseif($wid){
	    		    if(!D('Goodsstorage')->check_warehous_goods($wid,$goods_id,$num)){
	    		        returnApiError('仓库库存不足');
	    		    }
	    		}
    		} else { //购物车没有此物品，则插入
    			$goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);
    			$parent['goods_price'] = max($goods_price, 0);
    			$parent['goods_number'] = $num;
    			$parent['parent_id'] = 0;
    			$rec_id = M('cart')->add($parent);
    		}
    	}
    
    	//统计购物车总价
    	$cartres = $this->insert_cart_info(0,$uid,false);

//        卖鸡蛋
//        $user_rank = D('Users')->get_user_rank($uid);
//        if($user_rank['user_rank'] == 2){
//            $goodsModel = D('Goods');
//            $goodsId = $goodsModel->get_goods_by_goods_sn('S030101027111');
//
//            $cartModel = D('Cart');
//
//            $where = array(
//                'goods_id'  =>  $goodsId['goods_id'],
//            );
//            $cartGoods = $cartModel->where($where)->find();
//
//            if($cartres['amount'] >= 99){
//                if(empty($cartGoods)){
//                    $goods_price = D('Goods')->get_final_price($goodsId['goods_id'], 1, true, array(), $uid);
//
//                    $data = array(
//                        'user_id'       =>  $uid,
//                        'session_id'    =>  SESS_ID,
//                        'goods_id'      =>  $goodsId['goods_id'],
//                        'goods_sn'      =>  'S030101027111',
//                        'product_id'    =>  0,
//                        'goods_name'    =>  $goodsId['goods_name'],
//                        'market_price'  =>  $goodsId['market_price'],
//                        'goods_price'   =>  $goods_price,
//                        'goods_number'  =>  1,
//                        'parent_id'     =>  0,
//                    );
//
//                    if($goodsId['goods_number'] > 0 && $goodsId['is_on_sale'] == 1){
//                        $rec_id = M('cart')->add($data);
//                    }
//                }
//            }else{
//                if(!empty($cartGoods)){
//                    $where['session_id'] = SESS_ID;
//                    M('cart')->where($where)->delete();
//                }
//            }
//        }

    	//检查是否有赠品,如果有则添加到购物车
//     	$gift_goods = $this->check_gift_goods($goods_id, $uid,$cartres['amount'],$rec_id);
//     	if(count($gift_goods)>0){
//     		foreach ($gift_goods as $gift_key=>$val){
//     			$this->change_gift_goods($val, $uid,$num,$operate);
//     		}
//     	}
    	
    	/* 把赠品删除 */
//     	$where=array(
//     			'user_id'=>$uid,
//     			'is_gift'=>array('neq',0),
//     	);
//     	M('Cart')->where($where)->delete();
    	/* $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE session_id = '" . SESS_ID . "' AND is_gift != 0";
    	 $id=$Model->query($sql);*/

    	return true;
    }
    
    
    /**
     * 添加赠品到购物车
     * @param array $gift_goods	优惠商品
     * @param int $uid		用户id
     * @param int $num 数量
     * @param 
     */
	public function change_gift_goods($gift_goods,$uid,$num=1,$operate="add"){
		$map = array('parent_id'=>$gift_goods['parent_id'],'is_gift'=>$gift_goods['act_id'],'goods_id'=>$gift_goods['id']);
		$rec_data= $this->where($map)->find();
		switch ($operate){
			case "add":
				if(empty($rec_data) && (($gift_goods['act_type_ext']==0) || ($gift_goods['act_type_ext']>0 && $num <= $gift_goods['act_type_ext']))){
					$goods = M('goods')->where(array('goods_id'=>$gift_goods['id'],'is_on_sale'=>1,'is_delete'=>0))->find();
					if(!empty($goods)){
						$data = array(
								'user_id' => $uid,
								'session_id' => SESS_ID,
								'goods_id' => $goods['goods_id'],
								'goods_sn' => addslashes($goods['goods_sn']),
								'product_id' => 0,
								'goods_name' => addslashes($goods['goods_name']),
								'market_price' => $goods['market_price'],
								'goods_price'=>$gift_goods['price'],
								'goods_number'=>1,
								'parent_id'=>$gift_goods['parent_id'],
								'goods_attr' => "",
								'is_real' => $goods['is_real'],
								'extension_code' => $goods['extension_code'],
								'is_gift' => $gift_goods['act_id'],
								'is_quota' => 0,
								'is_shipping' => $goods['is_shipping'],
								'is_presell'=>$goods['is_presell'],
								'rec_type' => CART_GENERAL_GOODS
						);
						$this->add($data);
					}
				}else{
					if(($gift_goods['act_type_ext']==0) || ($gift_goods['act_type_ext']>0 && $num <= $gift_goods['act_type_ext'])){
						$data = array();
						$data['goods_price'] = $gift_goods['price'];
						$data['goods_number'] = $num;
						$this->where($map)->save($data);
					}
				}
			break;
			case "dec":
				if(!empty($rec_data)){
					if($num>0){
						$data = array();
						$data['goods_price'] = $gift_goods['price'];
						$data['goods_number'] = $num;
						$this->where($map)->save($data);
					}else{
						$this->where(array('rec_id'=>$rec_data['rec_id']))->delete();
					}
				}
			break;
			case "del":
				if(!empty($rec_data)){
						$this->where(array('rec_id'=>$rec_data['rec_id']))->delete();
				}
			break;
		}
	}
    
    /**
     * 获取送赠品或优惠购买
     * @param int $goods_id	商品id
     * @param int $uid 	用户id
     * @param int $total_price	购物车商品总额
     */
    public function check_gift_goods($goods_id, $uid, $total_price = 0,$parent_id=0) {
    	$favourable_gift = $this->favourable_gift_list_flow ( $uid, $total_price );
    	
    	$goods = M ( 'goods' )->where ( array ( 'goods_id' => $goods_id ) )->find ();
    	$gift_goods = array();
    	if (! empty ( $goods ) && count ( $favourable_gift ) > 0) {
    		foreach ( $favourable_gift as $key => $gift ) {
    			$flag = false;
    			switch ($gift ['act_rang']) {
    				case 1 :
    					if ($gift ['cate_id'] == $goods ['cat_id']) {
    						$flag = true;
    					}
    					break;
    				case 2 :
    					if ($gift ['brand_id'] == $goods ['brand_id']) {
    						$flag = true;
    					}
    					break;
    				case 3 :
    					if ($gift ['goods_id'] == $goods ['goods_id']) {
    						$flag = true;
    					}
    					break;
    				case 0:
    					$flag = true;
    					break;
    			}
    
    			if($flag){
    				if(!empty($gift['gift'])){
    					foreach ($gift['gift'] as $g_key=>$val){
    						$val['parent_id'] = $parent_id;
    						$val['act_id'] = $gift['act_id'];
    						$val['act_type_ext'] = $gift['act_type_ext'];
    						$gift_goods[] = $val;
    					}
    				}
    			}
    		}
    	}

    	return $gift_goods;
    }
    
    
    /**
     * 清空购物车
     * @param   int     $type   类型：默认普通商品
     */
    public function clear_cart($uid,$type = CART_GENERAL_GOODS,$rec_ids='') {
    	$map = array('user_id'=>$uid,'rec_type'=>$type);
    	if(!empty($rec_ids)){
    		$where['rec_id'] = array('in',explode(',', $rec_ids));
    		$where['parent_id'] = array('in',explode(',', $rec_ids));
    		$where['_logic'] = 'or';
    		$map['_complex'] = $where;
    	}
    	$res = $this->where($map)->delete();
    }
    
    /**
     * 调用购物车信息
     *
     * @access  public
     * @param $is_hd hd接口请求标志，0为H5；1为HD请求；
     * @param $uid 用户ID；
     * @return  string
     */
    public function insert_cart_info( $is_hd = 0, $uid = 0 ,$have_gift=true) {
    	if(!$have_gift){
    		$is_gift = " AND is_gift = 0";
    	}
        $sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .
                ' FROM ' . C('DB_PREFIX') . 'cart ' .
                " WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "'".$is_gift;

        $Model=new Model();
        $row = $Model->query($sql);
        $row=$row[0];
        if ($row) {
            $number = intval($row['number']);
            $amount = floatval($row['amount']);
        } else {
            $number = 0;
            $amount = 0;
        }

        return array('number'=>$number,'amount'=>$amount);
        /*$str = sprintf(L('cart_info'), $number, price_format($amount, false));
    
        return '<a href="flow.php" title="' . L('view_cart') . '">' . $str . '</a>';*/
    }
    
    
    public function get_shoppingcart_goods($is_hd = 0, $uid = 0,$wid=0,$rec_ids=0){
    	$goods_list = array();
    	$goods_outstock_list = array();
    	$goods_list_total = array(
    			'goods_price' => 0, // 本店售价合计（有格式）
    			'market_price' => 0, // 市场售价合计（有格式）
    			'saving' => 0, // 节省金额（有格式）
    			'save_rate' => 0, // 节省百分比
    			'goods_amount' => 0, // 本店售价合计（无格式）
    			'total_number' => 0,
    	);
    	$goods_outstock_list_total = array(
    			'goods_price' => 0, // 本店售价合计（有格式）
    			'market_price' => 0, // 市场售价合计（有格式）
    			'saving' => 0, // 节省金额（有格式）
    			'save_rate' => 0, // 节省百分比
    			'goods_amount' => 0, // 本店售价合计（无格式）
    			'total_number' => 0,
    	);
    	
    	$map = array();
    	if($rec_ids){
    		$map['c.rec_id'] = array('in',$rec_ids);
    	}
    	
    	$map['c.user_id'] = $uid;
    	$map['c.rec_type'] = CART_GENERAL_GOODS;
    	$map['c.user_id'] = $uid;
    	
    	$cart = D('cart');
    	$res = $cart->alias("c")
					    	->field("c.*,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid ,goods_weight,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.min_buy_num,g.goods_number as goods_stock,g.goods_thumb,g.goods_img,g.goods_brief,g.is_on_sale,g.promote_price,g.promote_end_date,g.promote_start_date")
					    	->join("left join ".C('DB_PREFIX')."goods g on c.goods_id=g.goods_id")
					    	->where($map)
					    	->order("c.rec_id asc")
					    	->select();
    	
    	/* 用于统计购物车中实体商品和虚拟商品的个数 */
    	$virtual_goods_count = 0;
    	$real_goods_count = 0;
    	$out_stock_real_goods_count = 0;
    	$out_stock_virtual_goods_count = 0;
    	$cart_goods_status_list = array();


    	 foreach ($res as $key=>$row) {
    	 	//如果是赠品或者优惠活动商品，主商品缺货，则不显示
    	 	if(($row['parent_id']>0 && empty($cart_goods_status_list[$row['parent_id']]['has_stock'])) || ($row['is_gift']>0 && $cart_goods_status_list[$row['parent_id']]['has_stock']==0)){
    	 		continue;
    	 	}
    	 	/* 查询规格 */
    	 	if (trim($row['goods_attr']) != '') {
    	 		$row['goods_attr'] = addslashes($row['goods_attr']);
    	 		$attr_list = D('goods_attr')->field("attr_value")->where(array('goods_attr_id'=>array("in",$row['goods_attr_id'])))->select();
    	 		foreach ($attr_list as $key=>$attr) {
    	 			$row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
    	 		}
    	 	}
    	 	$row['goods_thumb'] = img_init($row['goods_img']);

             /**
              * 判断促销价格是否已过期，过期后则自动获取商品最新价格
              */



//              获取vip对比价格
             $row['true_vip_price'] = trim(D('goods')->get_vip_price_for_all($row['goods_id']));
             $row['vip_price'] = trim(D('goods')->get_vip_price($row['goods_id']),$wid);



    	 	
    	 	if ($row['extension_code'] == 'package_buy') {
    	 		$row['package_goods_list'] = $this->get_package_goods($row['goods_id']);
    	 	}
    	 	//检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
    	 	$row['is_presell']=D('Goodsstorage')->check_whether_presell($row['goods_id'],$wid);
    	 	if($row['is_presell']){
    	 		if($row['delivery_type']==1){//分段发货
    	 			$Goodspreselltime=D('Goodspreselltime');
    	 			if($Goodspreselltime->check_shipping_goodspreselltime($row['goods_id'])){//检查预售商品是否设置发货配送时间
    	 				$preselltimeres=$Goodspreselltime->check_shippingtime($row['goods_id'],time());
    	 				if($preselltimeres){
    	 					$row['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);
    	 				}else{
    	 					$row['preselltimeres']=array('delivery_time'=>'');
    	 				}
    	 			}else{
    	 				$row['preselltimeres']=array('delivery_time'=>'');
    	 			}
    	 		}elseif($row['delivery_type']==2){ //定时方式
    	 			if($row['delivery_cycle']){
    	 				$gmd=local_date('Y-m-d',gmtime());
    	 				$goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$row['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
    	 				$row['preselltimeres']=array('delivery_time'=>$goods_presell_time);
    	 			}else{
    	 				$row['preselltimeres']=array('delivery_time'=>'');
    	 			}
    	 		}else{
    	 			$row['preselltimeres']=array('delivery_time'=>'');
    	 		}
    	 	}else{
    	 		$goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$row['goods_id']);
    	 		if($goodsstorage){
    	 			$row['goods_stock']=$goodsstorage['practical_num'];
    	 		}else{
    	 			$row['goods_stock']=0;
    	 		}
    	 		$row['preselltimeres']=array('delivery_time'=>'');
    	 	}
    	 	
    	 	$row['subtotal'] = price_format($row['goods_price'] * $row['goods_number'], false);
    	 	//如果添加到购物车的数量大于库存，则修改为库存数量
//    	 	dd($row['goods_price']);
    	 	if($row['goods_number']>$row['goods_stock'] && $row['goods_stock']>0){
    	 		$flag = $cart->where(array('rec_id'=>$row['rec_id']))->setField('goods_number',$row['goods_stock']);
    	 		if($flag!==false){
    	 			$row['goods_number'] = $row['goods_stock'];
    	 		}
    	 	}
    	 	if($row['spec_value']){
    	 		$row['spec_value'] =  $row['spec_value'];
    	 		$row['spec_unit'] =  $row['spec_unit'];
    	 	}elseif($row['goods_weight']){
    	 		$row['spec_value'] =  $row['goods_weight']*1000;
    	 		$row['spec_unit'] =  "g";
    	 	}
    	 	//查询此商品的商家批发折扣
    	 	$supply_discount = M("goods")->where(array("goods_id"=>$row['goods_id']))->getField("supply_discount");

    	 	if($supply_discount){
    	 	    $use_discount_array = array();
                $supply_discount = unserialize($supply_discount);
                foreach ($supply_discount as $r_key=>$value){
                    if($value['base']<=$row['goods_number']){
                        //可使用此优惠，在此所有优惠中查找最接近的优惠
                        $use_discount_array[$value['base']] = $value['discount'];
                    }
                }

                $now_discount = end($use_discount_array)/100;   //最接近的一个折扣率

            }


    	 	//拆分购物车中有库存与无库存商品
    	 	if($row['goods_stock']>0 && $row['is_on_sale']>0){
    	 		/* 统计实体商品和虚拟商品的个数 */
    	 		if ($row['is_real']) {
    	 			$real_goods_count++;
    	 		} else {
    	 			$virtual_goods_count++;
    	 		}
    	 		if($row['parent_id']==0){
    	 			$cart_goods_status_list[$row['rec_id']]['has_stock'] = 1;
    	 		}
    	 		//查询商家折扣

                M("goods")->where(array("goods_id"=>$row['goods_id']))->getField("supply_discount");


                $goods_list_total['total_number']+=$row['goods_number'];
                $goods_list_total['goods_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
                $goods_list_total['market_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
                $goods_list_total['shop_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
//                折扣满减
                $goods_list_total['discount_price'] += $row['benefit_price'];
                $goods_list[] = $row;

    	 	}else{
    	 		/* 统计缺货或者已下架实体商品和虚拟商品的个数 */
    	 		if ($row['is_real']) {
    	 			$out_stock_real_goods_count++;
    	 		} else {
    	 			$out_stock_virtual_goods_count++;
    	 		}
    	 		
    	 		if($row['parent_id']==0){
    	 			$cart_goods_status_list[$row['rec_id']]['has_stock'] = 0;
    	 		}

                /**
                 * 计算商品总价
                 */
    	 		$goods_outstock_list_total['total_number']+=$row['goods_number'];
    	 		$goods_outstock_list_total['goods_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
    	 		$goods_outstock_list_total['market_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
    	 		$goods_outstock_list_total['shop_price'] += $row['vip_price'] * $row['goods_number'] * $now_discount;
                //                折扣满减
                $goods_list_total['discount_price'] += $row['benefit_price'];
    	 		$goods_outstock_list[] = $row;
    	 	}
    	 }
    	 //统计购物车有货商品数量以及金额
    	 $goods_list_total['goods_amount'] = $goods_list_total['goods_price'];
    	 $goods_list_total['saving'] = price_format($goods_list_total['market_price'] - $goods_list_total['goods_price'], false);
    	 if ($goods_list_total['market_price'] > 0) {
    	 	$goods_list_total['save_rate'] = $goods_list_total['market_price'] ? round(($goods_list_total['market_price'] - $goods_list_total['goods_price']) *
    	 			100 / $goods_list_total['market_price']) . '%' : 0;
    	 }
    	 $goods_list_total['goods_price'] = price_format($goods_list_total['goods_price'], false);
    	 $goods_list_total['market_price'] = price_format($goods_list_total['market_price'], false);
    	 $goods_list_total['real_goods_count'] = $real_goods_count;
    	 $goods_list_total['virtual_goods_count'] = $virtual_goods_count;
		
    	 
    	 //统计购物车中缺货商品数量以及金额
    	 $goods_outstock_list_total['goods_amount'] = $goods_outstock_list_total['goods_price'];
    	 $goods_outstock_list_total['saving'] = price_format($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price'], false);
    	 if ($goods_outstock_list_total['market_price'] > 0) {
    	 	$goods_outstock_list_total['save_rate'] = $goods_outstock_list_total['market_price'] ? round(($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price']) *
    	 			100 / $goods_outstock_list_total['market_price']) . '%' : 0;
    	 }
    	 $goods_outstock_list_total['goods_price'] = price_format($goods_outstock_list_total['goods_price'], false);
    	 $goods_outstock_list_total['market_price'] = price_format($goods_outstock_list_total['market_price'], false);
    	 $goods_outstock_list_total['real_goods_count'] = $out_stock_real_goods_count;
    	 $goods_outstock_list_total['virtual_goods_count'] = $out_stock_virtual_goods_count;

//        dd($goods_list_total['goods_price']);

    	 return array('goods_list' => $goods_list, 'total' => $goods_list_total, 'goods_outstock_list'=>$goods_outstock_list,'out_stock_total'=>$goods_outstock_list_total);
    }

    /**
     * 插入活动id
     * Created by Jerry
     * @param $cart_id
     * @param $act_id
     * @return bool
     */
    protected function update_cart_for_act_id($cart_id, $act_id)
    {
        $where = array(
            'rec_id'    =>  $cart_id,
        );

        $rs = $this->where($where)->setField('act_id', $act_id);
        return $rs;
    }

    /**
     * 返回最新商品价格并修改
     * Created by Jerry
     * @param $goods_id
     * @param $cart_id
     * @return mixed
     */
    protected function update_cart_goods_price($goods_id, $cart_id, $price = false, $uid){
//        查询商品价格
        $goods_price = $this->get_goods_by_id_for_price($goods_id, $uid);

        $where = array(
            'rec_id'    =>  $cart_id,
        );
        $updateData = array(
            'goods_price'   =>  $goods_price,
        );

        if ($price) {
            $updateData['goods_price'] = $price;
        }

        $rs = $this->where($where)->save($updateData);

        return $goods_price;
    }

    /**
     * 返回商品价格
     * Created by Jerry
     * @param $goods_id
     * @return mixed
     */
    protected function get_goods_by_id_for_price($goods_id, $uid)
    {
        $goodsModel = D('Goods');
        return $goodsModel->get_final_price($goods_id,1,false,array(),$uid);
    }

    /**
     * 获得购物车中的商品
     *
     * @access  public
     * @param $is_hd 是否HD请求标识：默认值为0，0表示H5请求；1表示HD请求；主要解决HD没有SESS_ID问题，从而采用uid代替；
     * @param $uid 用户ID；
     * @return  array
     */
	public function get_cart_goods( $is_hd = 0, $uid = 0,$wid=0,$rec_ids=0) {
        /* 初始化 */
        $goods_list = array();
        $total = array(
            'goods_price' => 0, // 本店售价合计（有格式）
            'market_price' => 0, // 市场售价合计（有格式）
            'saving' => 0, // 节省金额（有格式）
            'save_rate' => 0, // 节省百分比
            'goods_amount' => 0, // 本店售价合计（无格式）
            'total_number' => 0,
        );
        if($rec_ids){
        	$recidstr = " AND c.rec_id in (".$rec_ids.")";
        }
//         if($wid){
//             /* 循环、统计 */
//             $sql = "SELECT c.*,gs.wid,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid ,g.spec_value,g.spec_unit,g.is_presell" .
//                 " FROM " . C('DB_PREFIX') . "cart c left join " . C('DB_PREFIX')."goods g on c.goods_id=g.goods_id left join ".C('DB_PREFIX')."goods_storage as gs on c.goods_id=gs.goods_id ".
//                 " WHERE c.user_id = '". $uid ."' AND c.rec_type='" . CART_GENERAL_GOODS . "'  AND gs.wid='".$wid.$recidstr.
//                 "' ORDER BY pid, c.parent_id";
//         }else{
//             /* 循环、统计 */
//             $sql = "SELECT c.*,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid ,g.spec_value,g.spec_unit,g.is_presell" .
//                 " FROM " . C('DB_PREFIX') . "cart c left join " . C('DB_PREFIX')."goods g on c.goods_id=g.goods_id".
//                 " WHERE c.user_id = '". $uid ."' AND c.rec_type='" . CART_GENERAL_GOODS . "'" .$recidstr.
//                 " ORDER BY pid, c.parent_id";
//         }
        
        /* 循环、统计 */
        $sql = "SELECT c.*,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid ,g.spec_value,g.spec_unit,g.is_presell as g_is_presell,g.delivery_type,g.delivery_cycle,g.min_buy_num" .
        		" FROM " . C('DB_PREFIX') . "cart c left join " . C('DB_PREFIX')."goods g on c.goods_id=g.goods_id".
        		" WHERE c.user_id = '". $uid ."' AND c.rec_type='" . CART_GENERAL_GOODS . "'" .$recidstr.
        		" ORDER BY pid, c.parent_id";
        
        $Model=new Model();
        $res = $Model->query($sql);
        /* 用于统计购物车中实体商品和虚拟商品的个数 */
        $virtual_goods_count = 0;
        $real_goods_count = 0;
        foreach ($res as $key=>$row) {
            $total['total_number']+=$row['goods_number'];
            $total['goods_price'] += $row['goods_price'] * $row['goods_number'];
            $total['market_price'] += $row['market_price'] * $row['goods_number'];
            $total['shop_price'] += $row['shop_price'] * $row['goods_number'];
            $row['subtotal'] = price_format($row['goods_price'] * $row['goods_number'], false);
            
            /// 前台不需要￥符，故注释；start cyb_2016-08-28
//             $row['goods_price'] = price_format($row['goods_price'], false);
//             $row['market_price'] = price_format($row['market_price'], false);
            /// 前台不需要￥符，故注释；end   cyb_2016-08-28
            
            /* 统计实体商品和虚拟商品的个数 */
            if ($row['is_real']) {
                $real_goods_count++;
            } else {
                $virtual_goods_count++;
            }
    
            /* 查询规格 */
            if (trim($row['goods_attr']) != '') {
                $row['goods_attr'] = addslashes($row['goods_attr']);
                $sql = "SELECT attr_value FROM " . C('DB_PREFIX') . "goods_attr WHERE goods_attr_id " .
                    db_create_in($row['goods_attr_id']);
                $attr_list = $Model->query($sql);
                foreach ($attr_list as $key=>$attr) {
                    $row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
                }
            }
            /* 增加是否在购物车里显示商品图 */
            if ((C('show_goods_in_cart') == "2" || C('show_goods_in_cart') == "3") && $row['extension_code'] != 'package_buy') {
                $res = $Model->query("SELECT `goods_thumb`,`goods_img` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
                $res =$res[0];
                $goods_thumb = img_init($res['goods_thumb']);
                $goods_img = img_init($res['goods_img']);
//                 $row['goods_thumb'] = get_image_path($row['goods_id'], $goods_thumb, true);
                $row['goods_img'] = $goods_img;
                $row['goods_thumb'] = $goods_img;
            }
            if ($row['extension_code'] == 'package_buy') {
                $row['package_goods_list'] = $this->get_package_goods($row['goods_id']);
            }
            //获取库存
//             if($wid){
//                 $res = $Model->query("SELECT `practical_num` FROM " . C('DB_PREFIX') . "goods_storage WHERE `goods_id`='{$row['goods_id']}' and wid=".$wid);
//                 $row['goods_max_number'] = $res[0]['practical_num'];
//                 $row['wid']=$wid;
//             }else{
//                 $res = $Model->query("SELECT `goods_number` FROM " . C('DB_PREFIX') . "goods WHERE `goods_id`='{$row['goods_id']}'");
//                 $row['goods_max_number'] = $res[0]['goods_number'];
//                 $row['wid']=0;
//             }
            //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
            $row['is_presell']=(int)$row['g_is_presell'];
            if($row['g_is_presell']!=0){
                $row['is_presell']=D('Goodsstorage')->check_whether_presell($row['goods_id'],$wid);
            }
            if($row['is_presell']){
                if($row['delivery_type']==1){//分段发货
                    $Goodspreselltime=D('Goodspreselltime');
                    if($Goodspreselltime->check_shipping_goodspreselltime($row['goods_id'])){//检查预售商品是否设置发货配送时间
                        $preselltimeres=$Goodspreselltime->check_shippingtime($row['goods_id'],time());
                        if($preselltimeres){
                            $row['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);
                        }else{
                            $row['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $row['preselltimeres']=array('delivery_time'=>'');
                    }
                }elseif($row['delivery_type']==2){ //定时方式
                    if($row['delivery_cycle']){
                        $gmd=local_date('Y-m-d',gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$row['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                        $row['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                    }else{
                        $row['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $row['preselltimeres']=array('delivery_time'=>'');
                }
            }else{
                $row['preselltimeres']=array('delivery_time'=>'');
            }
            $goods_list[$key] = $row;
        }
        $total['goods_amount'] = $total['goods_price'];
        $total['saving'] = price_format($total['market_price'] - $total['goods_price'], false);
        if ($total['market_price'] > 0) {
            $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) *
                100 / $total['market_price']) . '%' : 0;
        }
        $total['goods_price'] = price_format($total['goods_price'], false);
        $total['market_price'] = price_format($total['market_price'], false);
        $total['real_goods_count'] = $real_goods_count;
        $total['virtual_goods_count'] = $virtual_goods_count;
        //dump($goods_list);
        return array('goods_list' => $goods_list, 'total' => $total);
    }
    
    /**
     * 获取当前购物车的商品数
     * @param	int $uid
     */
    public function get_cart_count($uid){
    	$count = M('Cart')->where(array('user_id'=>$uid))->count();
    	return $count;
    }

	/**
     * 取得某用户等级当前时间可以享受的优惠活动
     *
     * @param int $user_rank
     *        	用户等级id，0表示非会员
     * @return array
     */
    public function favourable_list_flow($uid=0) {
    	$user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        /* 购物车中已有的优惠活动及数量 */
        $used_list = $this->cart_favourable($uid);
        /* 当前用户可享受的优惠活动 */
        $favourable_list = array();
        $user_rank = ',' . $user_rank . ',';
        $now = gmtime();
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "favourable_activity WHERE CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" . " AND start_time <= '$now' AND end_time >= '$now'" . " AND act_type = '" . FAT_GOODS . "'" . " ORDER BY sort_order";
        $Model=new Model();
        $favourable_activity_list = $Model->query($sql);
//        dd($favourable_activity_list);
        if($favourable_activity_list){
                foreach ($favourable_activity_list as $key=>$favourable) {
                    /*$favourable ['start_time'] = local_date(C('time_format'), $favourable ['start_time']);
                    $favourable ['end_time'] = local_date(C('time_format'), $favourable ['end_time']);*/
                    $favourable ['formated_min_amount'] = price_format($favourable ['min_amount'], false);
                    $favourable ['formated_max_amount'] = price_format($favourable ['max_amount'], false);
                    $favourable ['gift'] = unserialize($favourable ['gift']);
                    $favourable ['quota'] = unserialize($favourable ['quota']);

                    foreach ($favourable ['gift'] as $key => $value) {
                        $favourable ['gift'] [$key] ['formated_price'] = price_format($value ['price'], false);
                        $sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') . "goods WHERE is_on_sale = 1 AND goods_id = " . $value ['id'];
                        $res = $Model->query($sql);
                        $is_sale = $res[0]['count'];
                        if (!$is_sale) {
                            unset($favourable ['gift'] [$key]);
                        }
                    }
                    /*$favourable ['act_range_desc'] = $this->act_range_desc($favourable);
                    $favourable ['act_type_desc'] = sprintf(L('fat_ext.' . $favourable ['act_type']), $favourable ['act_type_ext']);*/

                    /* 是否能享受 */
                    $favourable ['available'] = $this->favourable_available($favourable,$uid);
                    if ($favourable ['available']) {
                        /* 是否尚未享受 */
                        $favourable ['available'] = !$this->favourable_used($favourable, $used_list);
                    }
                    if (!$favourable ['available']) {
                        continue;
                    }
                    $favourable_list [] = $favourable;
                }
                return $favourable_list;
        }else{
            return array();
        }
    }
    
    /**
     * 取得某用户等级当前可以享受的赠送优惠活动
     *
     * @param int $user_rank
     *        	用户等级id，0表示非会员
     * @return array
     */
    public function favourable_gift_list_flow($uid=0,$cart_price=0) {
    	$user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
    	/* 购物车中已有的优惠活动及数量 */
    	$used_list = $this->cart_favourable($uid);
    	/* 当前用户可享受的优惠活动 */
    	$favourable_list = array();
    	$user_rank = ',' . $user_rank . ',';
    	$now = gmtime();
    	$sql = "SELECT * FROM " . C('DB_PREFIX') . "favourable_activity WHERE CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" . " AND start_time <= '$now' AND end_time >= '$now'" . " AND act_type = '" . FAT_GOODS . "'" . " AND min_amount<=".$cart_price." AND ((max_amount>0 AND max_amount>=".$cart_price.") OR (max_amount<=0)) ORDER BY sort_order";
    	$Model=new Model();
    	$favourable_activity_list = $Model->query($sql);
    	if($favourable_activity_list){
    		foreach ($favourable_activity_list as $key=>$favourable) {
    			/*$favourable ['start_time'] = local_date(C('time_format'), $favourable ['start_time']);
    			 $favourable ['end_time'] = local_date(C('time_format'), $favourable ['end_time']);*/
    			$favourable ['formated_min_amount'] = price_format($favourable ['min_amount'], false);
    			$favourable ['formated_max_amount'] = price_format($favourable ['max_amount'], false);
    			$favourable ['gift'] = unserialize($favourable ['gift']);
    			$favourable ['quota'] = unserialize($favourable ['quota']);
    			foreach ($favourable ['gift'] as $key => $value) {
    				$favourable ['gift'] [$key] ['formated_price'] = price_format($value ['price'], false);
    				$sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') . "goods WHERE is_on_sale = 1 AND goods_id = " . $value ['id'];
    				$res = $Model->query($sql);
    				$is_sale = $res[0]['count'];
    				if (!$is_sale) {
    					unset($favourable ['gift'] [$key]);
    				}
    			}
    			/*$favourable ['act_range_desc'] = $this->act_range_desc($favourable);
    			 $favourable ['act_type_desc'] = sprintf(L('fat_ext.' . $favourable ['act_type']), $favourable ['act_type_ext']);*/
    			/* 是否能享受 */
    			$favourable ['available'] = $this->favourable_available($favourable,$uid);
    			if ($favourable ['available']) {
    				/* 是否尚未享受 */
    				$favourable ['available'] = !$this->favourable_used($favourable, $used_list);
    			}
    			if (!$favourable ['available']) {
    				continue;
    			}
    			$favourable_list [] = $favourable;
    		}
    		return $favourable_list;
    	}else{
    		return array();
    	}
    }
    
    
   /**
     * 取得购物车中已有的优惠活动及数量
     *
     * @return array
     */
    public function cart_favourable($user_id) {
        $list = array();
        $sql = "SELECT is_gift, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "cart  WHERE user_id = '" . $user_id . "'" . " AND rec_type = '" . CART_GENERAL_GOODS . "'" . " AND is_gift > 0" . " GROUP BY is_gift";
        $Model=new Model();
        $res = $Model->query($sql);
        foreach ($res as $key=>$row) {
            $list [$row ['is_gift']] = $row ['num'];
        }
        return $list;
    }
    
/**
     * 取得优惠范围描述
     *
     * @param array $favourable
     *        	优惠活动
     * @return string
     */
    public function act_range_desc($favourable) {

        if ($favourable ['act_range'] == FAR_BRAND) {
            $condition = "brand_id " . db_create_in($favourable ['act_range_ext']);
            $field = 'brand_name';
            $this->tableName = 'brand';
            $array = $this->field($field)->where($condition)->find();
            $array = $array ? $array : array();
            return join(',', $array);
        } elseif ($favourable ['act_range'] == FAR_CATEGORY) {
            $this->tableName = 'category';
            $condition = "cat_id " . db_create_in($favourable ['act_range_ext']);
            $field = 'cat_name';
            $array = $this->field($field)->where($condition)->find();
            $array = $array ? $array : array();
            return join(',', $array);
        } elseif ($favourable ['act_range'] == FAR_GOODS) {
            $this->tableName = 'goods';
            $condition = "goods_id " . db_create_in($favourable ['act_range_ext']);
            $field = 'goods_name';
            $array = $this->field($field)->where($condition)->find();
            $array = $array ? $array : array();
            return join(',', $array);
        } else {

            return '';
        }
    }
    
/**
     * 根据购物车判断是否可以享受某优惠活动
     *
     * @param array $favourable
     *        	优惠活动信息
     * @return bool
     */
   public function favourable_available($favourable,$uid=0) {
   		if($uid){
   			$user_rank  = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
   		}
        /* 会员等级是否符合 */
   		if(!in_array($user_rank, explode(',', $favourable ['user_rank']))){
   			return false;
   		}
//         if (strpos(',' . $favourable ['user_rank'] . ',', ',' . $user_rank . ',') === false) {
//             return false;
//         }

        /* 优惠范围内的商品总额 */
        $amount = $this->cart_favourable_amount($uid,$favourable);

        /* 金额上限为0表示没有上限 */
        return $amount >= $favourable ['min_amount'] && ($amount <= $favourable ['max_amount'] || $favourable ['max_amount'] == 0);
    }
    
    /**
     * 购物车中的限购产品
     */
    public function cart_favourable_quota($act_id, $goods_id = null,$uid='') {
    	$map = array();
    	$map['rec_type'] = CART_GENERAL_GOODS;
    	$map['is_quota'] = $act_id;
    	if($goods_id){
    		$map['goods_id'] = $goods_id;
    	}
    	
    	$map['user_id']  = $uid;
    	$res = $this->field("is_quota, SUM(goods_number) AS num")->where($map)->group('is_quota')->find();
    	return $res;
    }
    
    /**
     * 限购活动中的参与信息
     */
    public function activity_favourable_quota($act_id, $goods_id = null,$uid) {
    	$sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id'" . " GROUP BY act_id";
    	if ($goods_id) {
    		$sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id' AND goods_id=" . $goods_id . " GROUP BY act_id";
    	}
    	$model = new  Model();
    	$res =$model->query($sql);
    	return current($res);
    }
    
    /**
     * 添加限购产品
     */
    public function add_quota_to_cart($act_id, $id, $price,$uid) {
//     	$sql = "SELECT goods_number FROM " . C('DB_PREFIX') .
//     		"cart WHERE user_id = '" . $uid . "' AND goods_id = '$id' " .
//     		" AND is_quota='$act_id' " .
//     		" AND rec_type = '" . CART_GENERAL_GOODS . "'";
    	$map = array();
    	$map['user_id'] = $uid;
    	$map['goods_id'] = $id;
    	$map['is_quota'] = $act_id;
    	$map['rec_type'] = CART_GENERAL_GOODS;
    	$row = $this->where($map)->find();
    	if ($row) {
    		//如果购物车已经有此物品，则更新
    		$sql = "UPDATE " . C('DB_PREFIX') . "cart SET goods_number = goods_number+1" .
    					" , goods_price =goods_price+'$price'" .
    					" WHERE user_id = '" . $uid . "' AND goods_id = '$id' " .
    					" AND is_quota='$act_id' " .
    					"AND rec_type = '" . CART_GENERAL_GOODS . "'";
    	} else {
    		//购物车没有此物品，则插入
    		$sql = "INSERT INTO " . C('DB_PREFIX') . "cart (" . "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, " . "goods_number,goods_attr, is_real, extension_code, parent_id, is_gift,is_quota, rec_type,is_presell ) " . "SELECT '$uid', '" . SESS_ID . "', goods_id, goods_sn, goods_name, market_price, " . "'$price', 1,'', is_real, extension_code,0,0, '$act_id', '" . CART_GENERAL_GOODS . "',is_presell " . "FROM " . C('DB_PREFIX') . "goods WHERE goods_id = '$id'";
    	}
    	$res = $this->execute($sql);
    	return $res;
    }
    
    /**
     * 增减限购产品
     */
    public function change_quota_to_cart($act_id, $id, $price,$uid,$num) {
    	$map = array();
    	$map['user_id'] = $uid;
    	$map['goods_id'] = $id;
    	$map['is_quota'] = $act_id;
    	$map['rec_type'] = CART_GENERAL_GOODS;
    	$row = $this->where($map)->find();
    	if ($row) {
    		//如果购物车已经有此物品，则更新
    		$sql = "UPDATE " . C('DB_PREFIX') . "cart SET goods_number = goods_number+$num".
    				" WHERE user_id = '" . $uid . "' AND goods_id = '$id' " .
    				" AND is_quota='$act_id' " .
    				"AND rec_type = '" . CART_GENERAL_GOODS . "'";
    	} else {
    		//购物车没有此物品，则插入
    		$sql = "INSERT INTO " . C('DB_PREFIX') . "cart (" . "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, " . "goods_number,goods_attr, is_real, extension_code, parent_id, is_gift,is_quota, rec_type,is_presell ) " . "SELECT '$uid', '" . SESS_ID . "', goods_id, goods_sn, goods_name, market_price, " . "'$price', 1,'', is_real, extension_code,0,0, '$act_id', '" . CART_GENERAL_GOODS . "',is_presell " . "FROM " . C('DB_PREFIX') . "goods WHERE goods_id = '$id'";
    	}
    	$res = $this->execute($sql);
    	return $res;
    }

    /**
     * 返回指定商品的购物车数量
     * Created by Jerry
     * @param $uid
     * @param $goods_id
     * @param $act_id
     * @return mixed
     */
    public function get_cart_goods_number_by_id($uid, $goods_id)
    {
        $map['user_id'] = $uid;
        $map['goods_id'] = $goods_id;
        $map['rec_type'] = CART_GENERAL_GOODS;
        return $this->field('goods_number')->where($map)->find();
    }
    
    /**
     * 取得购物车中某优惠活动范围内的总金额
     *
     * @param array $favourable
     *        	优惠活动
     * @return float
     */
    public function cart_favourable_amount($uid,$favourable) {
        /* 查询优惠范围内商品总额的sql */
        $sql = "SELECT IFNULL(SUM(c.goods_price * c.goods_number),0) as sum " . "FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "goods AS g " . "WHERE c.goods_id = g.goods_id " . "AND c.user_id = '" . $uid . "' " . "AND c.rec_type = '" . CART_GENERAL_GOODS . "' " . "AND c.is_gift = 0 " . "AND c.goods_id > 0 ";
    
        /* 根据优惠范围修正sql */
        if ($favourable ['act_range'] == FAR_ALL) {
            // sql do not change
        } elseif ($favourable ['act_range'] == FAR_CATEGORY) {
            /* 取得优惠范围分类的所有下级分类 */
            $id_list = array();
            $cat_list = explode(',', $favourable ['act_range_ext']);
            foreach ($cat_list as $id) {
                $id_list = array_merge($id_list, array_keys($this->cat_list(intval($id), 0, false)));
            }
    
            $sql .= "AND g.cat_id " . db_create_in($id_list);
        } elseif ($favourable ['act_range'] == FAR_BRAND) {
            $id_list = explode(',', $favourable ['act_range_ext']);
    
            $sql .= "AND g.brand_id " . db_create_in($id_list);
        } else {
            $id_list = explode(',', $favourable ['act_range_ext']);
    
            $sql .= "AND g.goods_id " . db_create_in($id_list);
        }
        $Model=new Model();
        $res = $Model->query($sql);
        /* 优惠范围内的商品总额 */
        return $res[0]['sum'];
    }
    
    /**
     * 获得指定分类下的子分类的数组
     *
     * @access  public
     * @param   int     $cat_id     分类的ID
     * @param   int     $selected   当前选中分类的ID
     * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
     * @param   int     $level      限定返回的级数。为0时返回所有级数
     * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
     * @return  mix
     */
    public function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true) {
        static $res = NULL;
    
        if ($res === NULL) {
           $res = D('Category')->get_all_cat_list();
        }
    
        if (empty($res) == true) {
            return $re_type ? '' : array();
        }
    
        $options = $this->cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
    
        $children_level = 99999; //大于这个分类的将被删除
        if ($is_show_all == false) {
            foreach ($options as $key => $val) {
                if ($val['level'] > $children_level) {
                    unset($options[$key]);
                } else {
                    if ($val['is_show'] == 0) {
                        unset($options[$key]);
                        if ($children_level > $val['level']) {
                            $children_level = $val['level']; //标记一下，这样子分类也能删除
                        }
                    } else {
                        $children_level = 99999; //恢复初始值
                    }
                }
            }
        }
    
        /* 截取到指定的缩减级别 */
        if ($level > 0) {
            if ($cat_id == 0) {
                $end_level = $level;
            } else {
                $first_item = reset($options); // 获取第一个元素
                $end_level = $first_item['level'] + $level;
            }
    
            /* 保留level小于end_level的部分 */
            foreach ($options AS $key => $val) {
                if ($val['level'] >= $end_level) {
                    unset($options[$key]);
                }
            }
        }
    
        if ($re_type == true) {
            $select = '';
            foreach ($options AS $var) {
                $select .= '<option value="' . $var['cat_id'] . '" ';
                $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
                $select .= '>';
                if ($var['level'] > 0) {
                    $select .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select .= htmlspecialchars(addslashes($var['cat_name']), ENT_QUOTES) . '</option>';
            }
    
            return $select;
        } else {
            foreach ($options AS $key => $value) {
                $options[$key]['url'] = U('category/index', array('id' => $value['cat_id']));
            }
    
            return $options;
        }
    }
    
    /**
     * 过滤和排序所有分类，返回一个带有缩进级别的数组
     *
     * @access  private
     * @param   int     $cat_id     上级分类ID
     * @param   array   $arr        含有所有分类的数组
     * @param   int     $level      级别
     * @return  void
     */
    public function cat_options($spec_cat_id, $arr) {
        static $cat_options = array();
    
        if (isset($cat_options[$spec_cat_id])) {
            return $cat_options[$spec_cat_id];
        }
        if (!isset($cat_options[0])) {
            $level = $last_cat_id = 0;
            $options = $cat_id_array = $level_array = array(); 
                while (!empty($arr)) {
                    foreach ($arr AS $key => $value) {
                        $cat_id = $value['cat_id'];
                        if ($level == 0 && $last_cat_id == 0) {
                            if ($value['parent_id'] > 0) {
                                break;
                            }
                            $options[$cat_id] = $value;
                            $options[$cat_id]['level'] = $level;
                            $options[$cat_id]['id'] = $cat_id;
                            $options[$cat_id]['name'] = $value['cat_name'];
                            unset($arr[$key]);
    
                            if ($value['has_children'] == 0) {
                                continue;
                            }
                            $last_cat_id = $cat_id;
                            $cat_id_array = array($cat_id);
                            $level_array[$last_cat_id] = ++$level;
                            continue;
                        }
    
                        if ($value['parent_id'] == $last_cat_id) {
                            $options[$cat_id] = $value;
                            $options[$cat_id]['level'] = $level;
                            $options[$cat_id]['id'] = $cat_id;
                            $options[$cat_id]['name'] = $value['cat_name'];
                            unset($arr[$key]);
    
                            if ($value['has_children'] > 0) {
                                if (end($cat_id_array) != $last_cat_id) {
                                    $cat_id_array[] = $last_cat_id;
                                }
                                $last_cat_id = $cat_id;
                                $cat_id_array[] = $cat_id;
                                $level_array[$last_cat_id] = ++$level;
                            }
                        } elseif ($value['parent_id'] > $last_cat_id) {
                            break;
                        }
                    }
    
                    $count = count($cat_id_array);
                    if ($count > 1) {
                        $last_cat_id = array_pop($cat_id_array);
                    } elseif ($count == 1) {
                        if ($last_cat_id != end($cat_id_array)) {
                            $last_cat_id = end($cat_id_array);
                        } else {
                            $level = 0;
                            $last_cat_id = 0;
                            $cat_id_array = array();
                            continue;
                        }
                    }
    
                    if ($last_cat_id && isset($level_array[$last_cat_id])) {
                        $level = $level_array[$last_cat_id];
                    } else {
                        $level = 0;
                    }
                }   
            } else {
                $options = $data;
            }
            $cat_options[0] = $options;
        if (!$spec_cat_id) {
            return $options;
        } else {
            if (empty($options[$spec_cat_id])) {
                return array();
            }
    
            $spec_cat_id_level = $options[$spec_cat_id]['level'];
    
            foreach ($options AS $key => $value) {
                if ($key != $spec_cat_id) {
                    unset($options[$key]);
                } else {
                    break;
                }
            }
    
            $spec_cat_id_array = array();
            foreach ($options AS $key => $value) {
                if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                    ($spec_cat_id_level > $value['level'])) {
                        break;
                    } else {
                        $spec_cat_id_array[$key] = $value;
                    }
            }
            $cat_options[$spec_cat_id] = $spec_cat_id_array;
    
            return $spec_cat_id_array;
        }
    }
    
    
    /**
     * 购物车中是否已经有某优惠
     *
     * @param array $favourable
     *        	优惠活动
     * @param array $cart_favourable购物车中已有的优惠活动及数量
     */
    public function favourable_used($favourable, $cart_favourable) {
        switch ($favourable['act_type']) {
            case FAT_GOODS:
                return isset($cart_favourable [$favourable ['act_id']]) && $cart_favourable [$favourable ['act_id']] >= $favourable ['act_type_ext'] && $favourable ['act_type_ext'] > 0;
                break;
            case FAT_DISCOUNT_LIMIT:
                break;
            default:
                return isset($cart_favourable [$favourable ['act_id']]);
        }

//        if ($favourable ['act_type'] == FAT_GOODS) {
//            return isset($cart_favourable [$favourable ['act_id']]) && $cart_favourable [$favourable ['act_id']] >= $favourable ['act_type_ext'] && $favourable ['act_type_ext'] > 0;
//        } else {
//            return isset($cart_favourable [$favourable ['act_id']]);
//        }
    }


    protected function favourable_discount()
    {

    }
    
    
    /**
     * 计算折扣：根据购物车和优惠活动
     * @return  float   折扣
     */
    public function compute_discount($user_id) {
        /* 查询优惠活动 */
        $now = gmtime();
        $user_rank = D('users')->where(array('user_id'=>$user_id))->getField('user_rank');
        $user_rank = ',' . $user_rank . ',';
        $sql = "SELECT *" .
            "FROM " . C('DB_PREFIX') .
            "favourable_activity WHERE start_time <= '$now'" .
            " AND end_time >= '$now'" .
            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
        $Model=new Model();
        $favourable_list = $Model->query($sql);
        if (!$favourable_list) {
            return array('discount' => 0);
        }
    
        /* 查询购物车商品 */
        $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
            "FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "goods AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.user_id = '" . $user_id . "' " .
            "AND c.parent_id = 0 " .
            "AND c.is_gift = 0 " .
            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
        $goods_list = $Model->query($sql);
        if (!$goods_list) {
            return 0;
        }
    
        /* 初始化折扣 */
        $discount = 0;
        $favourable_name = array();
    
        /* 循环计算每个优惠活动的折扣 */
        foreach ($favourable_list as $key=> $favourable) {
            $total_amount = 0;
            if ($favourable['act_range'] == FAR_ALL) {
                foreach ($goods_list as $k=>$goods) {
                    $total_amount += $goods['subtotal'];
                }
            } elseif ($favourable['act_range'] == FAR_CATEGORY) {
                /* 找出分类id的子分类id */
                $id_list = array();
                $raw_id_list = explode(',', $favourable['act_range_ext']);
                foreach ($raw_id_list as $id) {
                    $id_list = array_merge($id_list, array_keys($this->cat_list($id, 0, false)));
                }
                $ids = join(',', array_unique($id_list));
    
                foreach ($goods_list as $k=>$goods) {
                    if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == FAR_BRAND) {
                foreach ($goods_list as $k=>$goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == FAR_GOODS) {
                foreach ($goods_list as $k=>$goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } else {
                continue;
            }
    
            /* 如果金额满足条件，累计折扣 */
            if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)) {
                if ($favourable['act_type'] == FAT_DISCOUNT) {
                    $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100);
    
                    $favourable_name[] = $favourable['act_name'];
                } elseif ($favourable['act_type'] == FAT_PRICE) {
                    $discount += $favourable['act_type_ext'];
    
                    $favourable_name[] = $favourable['act_name'];
                }
            }
        }
        //折扣减免金额大于订单额判断
        $discount = $total_amount >= $discount ? $discount : $total_amount;
        return array('discount' => $discount, 'name' => $favourable_name);
    }
    
    /**
     * 批量删除购物车指定商品
     * @param $uid 用户id；
     * @param $openid 微信用户唯一识别，可为空；
     * @param $is_hd hd请求标识,0为h5请求；1为hd请求；
     * @param $rec_str 购物车记录ID字串，多个用英语逗号隔开；
     * @return true成功；false失败；
     * @author 43
     */
    public function batch_del_cart_goods( $rec_str ,$uid) {
        $is_hd = 1;
        if(empty($uid)){
        	returnApiError('uid不存在');
        }
        
        $rec_str = explode( ',', $rec_str);
        if( empty($rec_str) ){
            returnApiError("rec_str is empty;");
        }
        $where["rec_id"] = array("in", $rec_str);
        $goods_list = $this->where($where)->select();
        
        $model = new Model();
        $rec_id_del_str = "";
        foreach ( $goods_list as $key => $goods ){
            /// 超值礼包
            if( $goods['extension_code'] == 'package_buy' ) {
                $rec_id_del_str .= $goods['rec_id'] . ',';

            /// 普通商品，同时删除所有赠品及其配件
            }else if( $goods['parent_id'] == 0 && $goods['is_gift'] == 0 ) {
                $rec_id_del_str .= $goods['rec_id'] . ',';
                /// 检查购物车中该普通商品的不可单独销售的配件并删除
                $parts_sql = "SELECT c.rec_id
    				FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "group_goods AS gg, " . C('DB_PREFIX') . "goods AS g
    				WHERE gg.parent_id = '" . $goods ['goods_id'] . "'
    				AND c.goods_id = gg.goods_id
    				AND c.parent_id = '" . $goods ['goods_id'] . "'
    				AND c.extension_code <> 'package_buy'
    				AND gg.goods_id = g.goods_id
    				AND g.is_alone_sale = 0";
                $parts_list = $model->query( $parts_sql );
                foreach ( $parts_list as $p_rec_id ){
                    $rec_id_del_str .= $p_rec_id["rec_id"] . ',';
                }

            /// 如果不是普通商品，只删除该商品即可
            }else{
                $rec_id_del_str .= $goods['rec_id'] . ',';
            }
        }
        
        $rec_id_del_str = trim( $rec_id_del_str, ',' );
        if( empty($rec_id_del_str) ) {
            return false;
        }
        
        $del_where["rec_id"] = array("in", $rec_id_del_str);
        $del_where["user_id"] = UID;
        
        $flag = $this->where( $del_where )->delete();
        if( !$flag ) {
            return false; 
        }
        
        // 删除购物车中不能单独销售的商品
        $this->flow_clear_cart_alone( $is_hd, $uid );
        return true;
    }
    
    /**
     * 删除购物车中的商品
     *
     * @access public
     * @param integer $id
     * @param $is_hd 是否为HD请求，0为h5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_drop_cart_goods( $id, $is_hd=0, $uid = 0 ) {
        /* 取得商品id */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id'";
//        dd($sql);
        $Model=new Model();
        $row = $Model->query($sql);
        $row = $row[0];
        if ($row) {
            // 如果是超值礼包
            if ($row ['extension_code'] == 'package_buy') {
                $sql = "DELETE FROM " . C('DB_PREFIX'). "cart WHERE user_id = '" . $uid . "' " . "AND rec_id = '$id' LIMIT 1";
            }
            // 如果是普通商品，同时删除所有赠品及其配件
            elseif ($row ['parent_id'] == 0 && $row ['is_gift'] == 0) {
                /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
                $sql = "SELECT c.rec_id
				FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "group_goods AS gg, " . C('DB_PREFIX') . "goods AS g
				WHERE gg.parent_id = '" . $row ['goods_id'] . "'
				AND c.goods_id = gg.goods_id
				AND c.parent_id = '" . $row ['goods_id'] . "'
				AND c.extension_code <> 'package_buy'
				AND gg.goods_id = g.goods_id
				AND g.is_alone_sale = 0";
                $res = $Model->query($sql);
                $_del_str = $id . ',';
                foreach ($res as $key=>$id_alone_sale_goods) {
                    $_del_str .= $id_alone_sale_goods ['rec_id'] . ',';
                }
                $_del_str = trim($_del_str, ',');
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id IN ($_del_str) OR parent_id = '$row[goods_id]' OR is_gift <> 0";
            }
            // 如果不是普通商品，只删除该商品即可
            else {
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id' LIMIT 1";
            }
            $Model->execute($sql);
        }else{
            return false;
        }
        //删除购物车中不能单独销售的商品
        $this->flow_clear_cart_alone( $is_hd, $uid );
        return true;
    }
    
    /**
     * 删除购物车中不能单独销售的商品
     *
     * @access public
     * @param $is_hd hd请求标志，0为H5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_clear_cart_alone( $is_hd=0, $uid=0 ) {
        /* 查询：购物车中所有不可以单独销售的配件 */
            $sql = "SELECT c.rec_id, gg.parent_id
    		FROM " . C('DB_PREFIX') . "cart AS c
    		LEFT JOIN " . C('DB_PREFIX') . "group_goods AS gg ON c.goods_id = gg.goods_id
    		LEFT JOIN " . C('DB_PREFIX') . "goods AS g ON c.goods_id = g.goods_id
    		WHERE c.user_id = '" . $uid . "'
    		AND c.extension_code <> 'package_buy'
    		AND gg.parent_id > 0
    		AND g.is_alone_sale = 0";

        $Model=new Model();
        $res = $Model->query($sql);
        $rec_id = array();
        foreach ($res as $key=>$row) {
            $rec_id [$row ['rec_id']] [] = $row ['parent_id'];
        }
        if (empty($rec_id)) {
            return;
        }
    
        /* 查询：购物车中所有商品 */
        $sql = "SELECT DISTINCT goods_id
    		FROM " . C('DB_PREFIX') .
                "cart WHERE user_id = '" . $uid . "'
    		AND extension_code <> 'package_buy'";
        
        $res = $Model->query($sql);
        $cart_good = array();
        foreach ($res as $key=>$row) {
            $cart_good [] = $row ['goods_id'];
        }
        if (empty($cart_good)) {
            return;
        }
    
        /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
        $del_rec_id = '';
        foreach ($rec_id as $key => $value) {
            foreach ($value as $v) {
                if (in_array($v, $cart_good)) {
                    continue 2;
                }
            }
    
            $del_rec_id = $key . ',';
        }
        $del_rec_id = trim($del_rec_id, ',');
    
        if ($del_rec_id == '') {
            return;
        }
    
        /* 删除 */
        
        /// HD请求处理
       	$sql = "DELETE FROM " . C('DB_PREFIX') .
            "cart WHERE user_id = '" . $uid . "'
            AND rec_id IN ($del_rec_id)";
        
        $Model->execute($sql);
    }
    
    
    /**
     * 取得购物车商品
     * @param   int     $type   类型：默认普通商品
     * @return  array   购物车商品数组
     */
    public function cart_goods($type = CART_GENERAL_GOODS,$rec_ids='',$uid=0,$wid=0) {
//         $sql = "SELECT rec_id, user_id, goods_id, goods_name, goods_sn, goods_number, " .
//             "market_price, goods_price, goods_attr, is_real, extension_code, parent_id, is_gift,is_quota, is_shipping,rec_type,is_presell, " .
//             "goods_price * goods_number AS subtotal " .
//             "FROM " . C('DB_PREFIX') .
//             "cart WHERE user_id = '" . $uid . "' " .
//             "AND rec_type='$type'";
//         if(!empty($rec_ids)){
//             $sql.=' and rec_id in('.$rec_ids.')';
//         }
//         $Model=new Model();
//         $arr = $Model->query($sql);
    	
        $where = array("user_id"=>$uid,"rec_type"=>$type);
    	if(!empty($rec_ids)){
            $where['rec_id'] = array('in',$rec_ids);
        }
        
        $arr = D("cart")->field("*,goods_price * goods_number as subtotal")->where($where)->select();

        /* 格式化价格及礼包商品 */
        foreach ($arr as $key => $value) {

            $arr[$key]['formated_market_price'] = price_format($value['market_price'], false);
            $arr[$key]['formated_goods_price'] = price_format($value['goods_price'], false);
            $arr[$key]['formated_subtotal'] = price_format($value['subtotal'], false);
            if ($value['extension_code'] == 'package_buy') {
                $arr[$key]['package_goods_list'] = $this->get_package_goods($value['goods_id']);
            }
//             $arr[$key]['goods_total_price'] = $value['goods_price']*$value['goods_number'];
			$arr[$key]['goods_total_price'] = $value['subtotal'];
            
            $goods = D('goods')->where(array('goods_id'=>$value['goods_id']))->find();
            $arr[$key]['goods_img'] = img_init($goods['goods_img']);
            $arr[$key]['is_auto_morrow_presell'] = $goods['is_auto_morrow_presell'];
            $arr[$key]['virtual_goods_number'] = $goods['goods_number'];
            $goods['is_presell']=(int)$goods['is_presell'];
            if($goods['is_presell']!=0){
              //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
              $is_presell=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid);
            }
            if($is_presell){
                $arr[$key]['is_presell']=1;
            	$arr[$key]['goods_stock'] =  $goods['goods_number'];
            	if($goods['delivery_type']==1){  //分段发货
            		$Goodspreselltime=D('Goodspreselltime');
            		if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
            			$preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
            			if($preselltimeres){
            				$arr[$key]['preselltimeres']=$preselltimeres;
            			}else{
            				$arr[$key]['preselltimeres']=array('delivery_time'=>'');
            			}
            		}else{
            			$arr[$key]['preselltimeres']=array('delivery_time'=>'');
            		}
            	}elseif($goods['delivery_type']==2){ //定时方式
            		if($goods['delivery_cycle']){
            			$gmd=local_date('Y-m-d',gmtime());
            			$goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
            			$arr[$key]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
            		}else{
            			$arr[$key]['preselltimeres']=array('delivery_time'=>'');
            		}
            	}else{
            		$arr[$key]['preselltimeres']=array('delivery_time'=>'');
            	}
            
            }else{
                $arr[$key]['is_presell']=0;
            	$goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$goods['goods_id']);
            	if($goodsstorage){
            		$arr[$key]['goods_stock']=$goodsstorage['practical_num'];
            	}else{
            		$arr[$key]['goods_stock']=0;
            	}
            	$arr[$key]['preselltimeres']=array('delivery_time'=>'');
            }
            
            //如果商品名有变动，则修改购物车中的商品名
            if($arr[$key]['goods_name']!=$goods['goods_name']){
            	$arr[$key]['goods_name'] = $goods['goods_name'];
            	M('cart')->where(array('rec_id'=>$value['rec_id']))->setField('goods_name',$goods['goods_name']);
            }
            
        }

        return $arr;
    }
    
    /**
     * 获得指定礼包的商品
     *
     * @access  public
     * @param   integer $package_id
     * @return  array
     */
    public function get_package_goods($package_id) {
        $sql = "SELECT pg.goods_id, g.goods_name, pg.goods_number, p.goods_attr, p.product_number, p.product_id
            FROM " . C('DB_PREFIX') . 'package_goods ' . " AS pg
                LEFT JOIN " . C('DB_PREFIX') . 'goods ' . " AS g ON pg.goods_id = g.goods_id
                LEFT JOIN " . C('DB_PREFIX') . 'products ' . " AS p ON pg.product_id = p.product_id
                    WHERE pg.package_id = '$package_id'";
        if ($package_id == 0) {
            $sql .= " AND pg.admin_id = '$_SESSION[admin_id]'";
        }
        $Model=new Model();
        $resource = $Model->query($sql);
        if (!$resource) {
            return array();
        }
    
        $row = array();
    
        /* 生成结果数组 取存在货品的商品id 组合商品id与货品id */
        $good_product_str = '';
        foreach ($resource as $key=>$_row){
            if ($_row['product_id'] > 0) {
                /* 取存商品id */
                $good_product_str .= ',' . $_row['goods_id'];
    
                /* 组合商品id与货品id */
                $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id'];
            } else {
                /* 组合商品id与货品id */
                $_row['g_p'] = $_row['goods_id'];
            }
    
            //生成结果数组
            $row[] = $_row;
        }
        $good_product_str = trim($good_product_str, ',');
    
        /* 释放空间 */
        unset($resource, $_row, $sql);
    
        /* 取商品属性 */
        if ($good_product_str != '') {
            $sql = "SELECT goods_attr_id, attr_value FROM " . C('DB_PREFIX') . 'goods_attr' . " WHERE goods_id IN ($good_product_str)";
            
            $result_goods_attr = $Model->query($sql);
    
            $_goods_attr = array();
            foreach ($result_goods_attr as $key=>$value) {
                $_goods_attr[$value['goods_attr_id']] = $value['attr_value'];
            }
        }
    
        /* 过滤货品 */
        $format[0] = '%s[%s]--[%d]';
        $format[1] = '%s--[%d]';
        foreach ($row as $key => $value) {
            if ($value['goods_attr'] != '') {
                $goods_attr_array = explode('|', $value['goods_attr']);
    
                $goods_attr = array();
                foreach ($goods_attr_array as $_attr) {
                    $goods_attr[] = $_goods_attr[$_attr];
                }
    
                $row[$key]['goods_name'] = sprintf($format[0], $value['goods_name'], implode('，', $goods_attr), $value['goods_number']);
            } else {
                $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['goods_number']);
            }
        }
    
        return $row;
    }
    
    /**
     * 根据订单中的商品总额来获得包装的费用
     *
     * @access  public
     * @param   integer $pack_id
     * @param   float   $goods_amount
     * @return  float
     */
    public function pack_fee($pack_id, $goods_amount) {
        $pack = $this->pack_info($pack_id);
    
        $val = (floatval($pack['free_money']) <= $goods_amount && $pack['free_money'] > 0) ? 0 : floatval($pack['pack_fee']);
    
        return $val;
    }
    
    /**
     * 取得包装信息
     * @param   int     $pack_id    包装id
     * @return  array   包装信息
     */
    public function pack_info($pack_id) {
        $sql = "SELECT * FROM " . C('DB_PREFIX') .
        "pack WHERE pack_id = '$pack_id'";
        $Model=new Model();
        $row=$Model->query($sql);
        return $row[0];
    }
   
    /**
     * 根据订单中商品总额获得需要支付的贺卡费用
     *
     * @access  public
     * @param   integer $card_id
     * @param   float   $goods_amount
     * @return  float
     */
    public function card_fee($card_id, $goods_amount) {
        $card = $this->card_info($card_id);
    
        return ($card['free_money'] <= $goods_amount && $card['free_money'] > 0) ? 0 : $card['card_fee'];
    }
    
    /**
     * 取得贺卡信息
     * @param   int     $card_id    贺卡id
     * @return  array   贺卡信息
     */
    public function card_info($card_id) {
        $sql = "SELECT * FROM " . C('DB_PREFIX') .
        "card WHERE card_id = '$card_id'";
        $Model=new Model();
        $row=$Model->query($sql);
        return $row[0];
    }
    
    /**
     * 取得红包信息
     * @param   int     $bonus_id   红包id
     * @param   string  $bonus_sn   红包序列号
     * @param   array   红包信息
     */
    public function bonus_info($bonus_id, $bonus_sn = '') {
        $sql = "SELECT t.*, b.* " .
            "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
            C('DB_PREFIX') . "user_bonus AS b " .
            "WHERE t.type_id = b.bonus_type_id ";
        if ($bonus_id > 0) {
            $sql .= "AND b.bonus_id = '$bonus_id'";
        } else {
            $sql .= "AND b.bonus_sn = '$bonus_sn'";
        }
        $sql .=' limit 1';
        $Model=new Model();
        $row=$Model->query($sql);
        return $row[0];
    }
    
    
    /**
     * 取得某订单商品总重量和总金额（对应 cart_weight_price）
     * @param   int     $order_id   订单id
     * @return  array   ('weight' => **, 'amount' => **, 'formated_weight' => **)
     */
    public function order_weight_price($order_id) {
        $sql = "SELECT SUM(g.goods_weight * o.goods_number) AS weight, " .
            "SUM(o.goods_price * o.goods_number) AS amount ," .
            "SUM(o.goods_number) AS number " .
            "FROM " . C('DB_PREFIX') . "order_goods AS o, " .
            C('DB_PREFIX') . "goods AS g " .
            "WHERE o.order_id = '$order_id' " .
            "AND o.goods_id = g.goods_id limit 1";
        $Model=new Model();
        $row=$Model->query($sql);
        $row = $row[0];
        $row['weight'] = floatval($row['weight']);
        $row['amount'] = floatval($row['amount']);
        $row['number'] = intval($row['number']);
    
        /* 格式化重量 */
        $row['formated_weight'] = formated_weight($row['weight']);
    
        return $row;
    }
    
    
    /**
     * 计算购物车中的商品能享受红包支付的总额
     * @return  float   享受红包支付的总额
     */
    public function compute_discount_amount($user_id) {
        /* 查询优惠活动 */
        $now = gmtime();
        $user_rank = D('users')->where(array('user_id'=>$user_id))->getField('user_rank');
        $user_rank = ',' . $user_rank . ',';
        $sql = "SELECT *" .
            "FROM " . C('DB_PREFIX') .
            "favourable_activity WHERE start_time <= '$now'" .
            " AND end_time >= '$now'" .
            " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" .
            " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE));
        $Model=new Model();
        $favourable_list = $Model->query($sql);
        if (!$favourable_list) {
            return 0;
        }
    
        /* 查询购物车商品 */
        $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " .
            "FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "goods AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.user_id = '" . $user_id . "' " .
            "AND c.parent_id = 0 " .
            "AND c.is_gift = 0 " .
            "AND rec_type = '" . CART_GENERAL_GOODS . "'";
        $goods_list = $Model->query($sql);
        if (!$goods_list) {
            return 0;
        }
    
        /* 初始化折扣 */
        $discount = 0;
        $favourable_name = array();
    
        /* 循环计算每个优惠活动的折扣 */
        foreach ($favourable_list as $key=>$favourable) {
            $total_amount = 0;
            if ($favourable['act_range'] == FAR_ALL) {
                foreach ($goods_list as $goods) {
                    $total_amount += $goods['subtotal'];
                }
            } elseif ($favourable['act_range'] == FAR_CATEGORY) {
                /* 找出分类id的子分类id */
                $id_list = array();
                $raw_id_list = explode(',', $favourable['act_range_ext']);
                foreach ($raw_id_list as $id) {
                    $id_list = array_merge($id_list, array_keys($this->cat_list($id, 0, false)));
                }
                $ids = join(',', array_unique($id_list));
    
                foreach ($goods_list as $key=>$goods) {
                    if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == FAR_BRAND) {
                foreach ($goods_list as $goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } elseif ($favourable['act_range'] == FAR_GOODS) {
                foreach ($goods_list as $goods) {
                    if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false) {
                        $total_amount += $goods['subtotal'];
                    }
                }
            } else {
                continue;
            }
            if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)) {
                if ($favourable['act_type'] == FAT_DISCOUNT) {
                    $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100);
                } elseif ($favourable['act_type'] == FAT_PRICE) {
                    $discount += $favourable['act_type_ext'];
                }
            }
        }
        //折扣减免金额大于订单额判断
        $discount = $total_amount >= $discount ? $discount : $total_amount;
        return $discount;
    }
    
    /**
     * 取得购物车该赠送的积分数
     * @return  int     积分数
     */
    public function get_give_integral($goods,$user_id) {
        $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" .
            " as count FROM " . C('DB_PREFIX') . "cart AS c, " .
            C('DB_PREFIX') . "goods AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.user_id = '" . $user_id . "' " .
            "AND c.goods_id > 0 " .
            "AND c.parent_id = 0 " .
            "AND c.rec_type = 0 " .
            "AND c.is_gift = 0 limit 1";
        $Model=new Model();
        $res = $Model->query($sql);
        return intval($res[0]['count']);
    }
    
    
    /**
     * 取得当前用户应该得到的红包总额
     */
    public function get_total_bonus($user_id) {
        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
    
        /* 按商品发的红包 */
        $sql = "SELECT SUM(c.goods_number * t.type_money)" .
            " as count FROM " . C('DB_PREFIX') . "cart AS c, "
                . C('DB_PREFIX') . "bonus_type AS t, "
                    . C('DB_PREFIX') . "goods AS g " .
                    "WHERE c.user_id = '" . $user_id . "' " .
                    "AND c.is_gift = 0 " .
                    "AND c.goods_id = g.goods_id " .
                    "AND g.bonus_type_id = t.type_id " .
                    "AND t.send_type = '" . SEND_BY_GOODS . "' " .
                    "AND t.send_start_date <= '$today' " .
                    "AND t.send_end_date >= '$today' " .
                    "AND c.rec_type = '" . CART_GENERAL_GOODS . "' limit 1";
        $Model=new Model();
        $res = $Model->query($sql);
        $res=$res[0];
        $goods_total = floatval($res['count']);
    
        /* 取得购物车中非赠品总金额 */
        $sql = "SELECT SUM(goods_price * goods_number) " .
            " as count FROM " . C('DB_PREFIX') .
            "cart WHERE user_id = '" . $user_id . "' " .
            " AND is_gift = 0 " .
            " AND rec_type = '" . CART_GENERAL_GOODS . "' limit 1";
        $res = $Model->query($sql);
        $res=$res[0];
        $amount = floatval($res['count']);
    
        /* 按订单发的红包 */
        $sql = "SELECT FLOOR('$amount' / min_amount) * type_money " .
        "as count FROM " . C('DB_PREFIX') .
        "bonus_type WHERE send_type = '" . SEND_BY_ORDER . "' " .
        " AND send_start_date <= '$today' " .
        "AND send_end_date >= '$today' " .
        "AND min_amount > 0  limit 1";
        $res = $Model->query($sql);
        $res=$res[0];
        $order_total = floatval($res['count']);
    
        return $goods_total + $order_total;
    }
    
    
    /**
     * 取得购物车总金额
     * @params  boolean $include_gift   是否包括赠品
     * @param   int     $type           类型：默认普通商品
     * @return  float   购物车总金额
     */
    public function cart_amount($include_gift = true, $type = CART_GENERAL_GOODS,$user_id) {
        $sql = "SELECT SUM(goods_price * goods_number) " .
            " as amount FROM " . C('DB_PREFIX') .
            "cart WHERE user_id = '" . $user_id . "' " .
            "AND rec_type = '$type' ";
    
        if (!$include_gift) {
            $sql .= ' AND is_gift = 0 AND goods_id > 0';
        }
        $sql.=' limit 1';
        $Model=new Model();
        $res = $Model->query($sql);
        return floatval($res[0]['amount']);
    }
    
    /**
     * 取得可用的支付方式列表
     * @param   bool    $support_cod        配送方式是否支持货到付款
     * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
     * @param   int     $is_online          是否支持在线支付
     * @return  array   配送方式数组
     */
    public function available_payment_list($support_cod, $cod_fee = 0, $is_online = false) {
        $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
            ' FROM ' . C('DB_PREFIX') . 'payment WHERE enabled = 1 ';
        if (!$support_cod) {
            $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
        }
        if ($is_online) {
            $sql .= "AND is_online = '1' ";
        }
        $sql .= 'ORDER BY pay_order'; // 排序
        $Model=new Model();
        $res = $Model->query($sql);
    
        $pay_list = array();
        foreach ($res as $key => $row) {
            if ($row['is_cod'] == '1') {
                $row['pay_fee'] = $cod_fee;
            }
            $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
            price_format($row['pay_fee'], false);
            $modules[] = $row;
        }
        if (isset($modules)) {
            return $modules;
        }
    }
    
    /**
     * 取得包装列表
     * @return  array   包装列表
     */
    public function pack_list() {
        $sql = 'SELECT * FROM ' . C('DB_PREFIX') . "pack";
        $Model=new Model();
        $res = $Model->query($sql);
        $list = array();
        foreach ($res as $key => $row) {
            $row['format_pack_fee'] = price_format($row['pack_fee'], false);
            $row['format_free_money'] = price_format($row['free_money'], false);
            $list[] = $row;
        }
        return $list;
    }
    
    /**
     * 取得贺卡列表
     * @return  array   贺卡列表
     */
    public function card_list() {
        $sql = "SELECT * FROM " . C('DB_PREFIX') . 'card';
        $Model=new Model();
        $res = $Model->query($sql);
        $list = array();
        foreach ($res as $key=>$row) {
            $row['format_card_fee'] = price_format($row['card_fee'], false);
            $row['format_free_money'] = price_format($row['free_money'], false);
            $list[] = $row;
        }
        return $list;
    }
    
    /**
     * 取得用户信息
     * @param   int     $user_id    用户id
     * @return  array   用户信息
     */
    public function user_info($user_id) {
        $sql = "SELECT * FROM " . C('DB_PREFIX') .
        "users WHERE user_id = '$user_id' limit 1";
        $Model=new Model();
        $res = $Model->query($sql);
        $user = $res[0];
        unset($user['question']);
        unset($user['answer']);
    
        /* 格式化帐户余额 */
        if ($user) {
            $user['formated_user_money'] = price_format($user['user_money'], false);
            $user['formated_frozen_money'] = price_format($user['frozen_money'], false);
        }
        return $user;
    }
    
    
    /**
     * 获得用户的可用积分
     *
     * @access private
     * @return integral
     */
    public function flow_available_points($user_id) {
        $sql = "SELECT SUM(g.integral * c.goods_number) as sum " . "FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "goods AS g " . "WHERE c.user_id = '" . $user_id . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " . "AND c.rec_type = '" . CART_GENERAL_GOODS . "' limit 1";
        $Model=new Model();
        $res = $Model->query($sql);
        $val = intval($res[0]['sum']);
    
        return integral_of_value($val);
    }
    
    /**
     * 取得用户当前可用红包
     * @param   int     $user_id        用户id
     * @param   float   $goods_amount   订单商品金额
     * @param array		订单商品
     * @return  array   红包数组
     */
    public function user_bonus($user_id, $goods_amount = 0,$cart_goods = array()) {
        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
    
        $sql = "SELECT t.type_id, t.type_name, t.type_money, t.is_limit_buy,b.bonus_id,t.use_start_date,t.use_end_date,t.min_goods_amount,t.has_effective_days,t.effective_days,b.deadline " .
            "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
            C('DB_PREFIX')  . "user_bonus AS b " .
            "WHERE t.type_id = b.bonus_type_id " .
            "AND t.use_start_date <= '$today' " .
//            "AND t.use_end_date >= '$today' " .
            "AND t.min_goods_amount <= '$goods_amount' " .
            "AND b.user_id<>0 " .
            "AND b.user_id = '$user_id' " .
            "AND b.order_id = 0 ".
            "AND t.bonus_type = 0"; //只获取订单金额抵扣红包
        $Model=new Model();
        //dump($sql);
        $bonus_list = $Model->query($sql);
        
        if(!empty($bonus_list) && count($cart_goods)>0){
        	$bonus_list = $this->check_canuse_bonus($bonus_list,$cart_goods);
        }
        return $bonus_list;
    }

    /**
     * 获取用户的运费抵扣卷
     * @param $user_id  用户ID
     * @param $start_price  起送金额
     * @param $order_amount 用户订单
     */
    public function user_bonus_freight($user_id, $start_price, $order_amount){
        //当前只有39区域且订单金额小于39的用户才会使用运费红包
        if ($start_price==39&&$order_amount<39){

            $day = getdate();
            $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

            $sql = "SELECT t.type_id, t.type_name, t.type_money, t.is_limit_buy,b.bonus_id,t.use_start_date,t.use_end_date,t.min_goods_amount,t.has_effective_days,t.effective_days,b.deadline " .
                "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
                C('DB_PREFIX')  . "user_bonus AS b " .
                "WHERE t.type_id = b.bonus_type_id " .
                "AND t.use_start_date <= '$today' " .
                "AND t.use_end_date >= '$today' " .
                "AND b.user_id<>0 " .
                "AND b.user_id = '$user_id' " .
                "AND b.order_id = 0 ".
                "AND t.bonus_type = 1"; //
            $Model=new Model();
            $bonus_list = $Model->query($sql);
            $now = gmtime();

            if(!empty($bonus_list)){
                foreach ($bonus_list as $key=>$value){
                    if($value['deadline']>0 && $now>$value['deadline']){
                        unset($bonus_list[$key]);
                        continue;
                    }elseif($value['deadline'] == 0  && $now > $value['use_end_date']){
                        unset($bonus_list[$key]);
                        continue;
                    }
                }
                return $bonus_list;
            }
        }

    }
    
    /**
     * 检查红包是否符合使用限制条件
     * @param array $bonus_list
     * @param array $cart_goods
     */
    private function check_canuse_bonus($bonus_list,$cart_goods){
    	$goods_ids = array();
    	foreach ($cart_goods as $goods){
    		$goods_ids[] = $goods['goods_id'];
    	}
    	
    	//获取当前购物车中商品id,所属分类以及品牌
    	$where = array('goods_id'=>array('in',$goods_ids));
    	$data = M('goods')->where($where)->select();
    	
    	$goods_id_list = array();
    	$goods_cat_id_list = array();
    	$goods_brand_id_list = array();
    	
    	foreach ($data as $val){
    		if(!in_array($val["goods_id"], $goods_id_list)){
    			$goods_id_list[] = $val["goods_id"];
    		}
    		if(!in_array($val["cat_id"], $goods_cat_id_list)){
    			$goods_cat_id_list[] = $val["cat_id"];
    		}
    		if(!in_array($val["brand_id"], $goods_brand_id_list)){
    			$goods_brand_id_list[] = $val["brand_id"];
    		}
    	}
    	
    	$can_use_bonus = array();
        $now = gmtime();
    	//检查商品是否在红包使用限制范围内
    	foreach ($bonus_list as $key=>$bonus){
            if($bonus['deadline']>0 && $now>$bonus['deadline']){
                unset($bonus_list[$key]);
                continue;
            }elseif($bonus['deadline'] == 0  && $now > $bonus['use_end_date']){
                unset($bonus_list[$key]);
                continue;
            }
    		$bonus_list[$key]['use_start_date'] = local_date("Y-m-d H:i:s",$bonus['use_start_date']);
    		$bonus_list[$key]['use_end_date'] = local_date("Y-m-d H:i:s",$bonus['use_end_date']);
    		$bonus_list[$key]['min_goods_amount'] = $bonus['min_goods_amount'];
    		if(!$bonus['is_limit_buy']){
    			$can_use_bonus[] = $bonus_list[$key];
    			continue;
    		}
    		$config = M('bonus_config')->where(array("bonus_type_id"=>$bonus["type_id"],"status"=>1))->select();
    		if(empty($config)){
    			$can_use_bonus[] = $bonus_list[$key];
    			continue;
    		}
    		$flag = false;
    		foreach ($config as $cfg_key=>$val_cfig){
    			switch ($val_cfig['act_rang']){
    				case 1:
    					if(in_array($val_cfig['cate_id'], $goods_cat_id_list)){
    						$flag = true;
    					}
    				break;
    				case 2:
    					if(in_array($val_cfig['brand_id'], $goods_brand_id_list)){
    						$flag = true;
    					}
    				break;
    				case 3:
    					if(in_array($val_cfig['goods_id'], $goods_id_list)){
    						$flag = true;
    					}
    				break;
    			}
    			if($flag){
    				break;
    			}
    		}
    		if($flag==false){
    			unset($bonus_list[$key]);
    		}else{
    			$can_use_bonus[] = $bonus_list[$key];
    		}
    		
    	}
    	return $can_use_bonus;
    }
    
    
    /**
     * 获得购物车中商品的总重量、总价格、总数量
     *
     * @access  public
     * @param   int     $type   类型：默认普通商品
     * @return  array
     */
    public function cart_weight_price($user_id,$type = CART_GENERAL_GOODS) {
        $package_row['weight'] = 0;
        $package_row['amount'] = 0;
        $package_row['number'] = 0;
    
        $packages_row['free_shipping'] = 1;
    
        /* 计算超值礼包内商品的相关配送参数 */
        $sql = 'SELECT goods_id, goods_number, goods_price FROM ' . C('DB_PREFIX') . "cart WHERE extension_code = 'package_buy' AND user_id = '" . $user_id . "'";
        $Model=new Model();
        $row = $Model->query($sql);
    
        if ($row) {
            $packages_row['free_shipping'] = 0;
            $free_shipping_count = 0;
    
            foreach ($row as $key=>$val) {
                // 如果商品全为免运费商品，设置一个标识变量
                $sql = 'SELECT count(*) as count FROM ' .
                    C('DB_PREFIX') . 'package_goods AS pg, ' .
                    C('DB_PREFIX') . 'goods AS g ' .
                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "' limit 1";
                $res = $Model->query($sql);
                $shipping_count = $res[0]['count'];
    
                if ($shipping_count > 0) {
                    // 循环计算每个超值礼包商品的重量和数量，注意一个礼包中可能包换若干个同一商品
                    $sql = 'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' .
                        'SUM(pg.goods_number) AS number FROM ' .
                        C('DB_PREFIX') . 'package_goods AS pg, ' .
                        C('DB_PREFIX') . 'goods AS g ' .
                        "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "' limit 1";
    
                    $goods_row = $Model->query($sql);
                    $goods_row=$goods_row[0];
                    $package_row['weight'] += floatval($goods_row['weight']) * $val['goods_number'];
                    $package_row['amount'] += floatval($val['goods_price']) * $val['goods_number'];
                    $package_row['number'] += intval($goods_row['number']) * $val['goods_number'];
                } else {
                    $free_shipping_count++;
                }
            }
    
            $packages_row['free_shipping'] = $free_shipping_count == count($row) ? 1 : 0;
        }
    
        /* 获得购物车中非超值礼包商品的总重量 */
        $sql = 'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
            'SUM(c.goods_price * c.goods_number) AS amount, ' .
            'SUM(c.goods_number) AS number ' .
            'FROM ' . C('DB_PREFIX') . 'cart AS c ' .
            'LEFT JOIN ' . C('DB_PREFIX') . 'goods AS g ON g.goods_id = c.goods_id ' .
            "WHERE c.user_id = '" . $user_id . "' " .
            "AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy' limit 1";
        $row = $Model->query($sql);
        $row=$row[0];
        $packages_row['weight'] = floatval($row['weight']) + $package_row['weight'];
        $packages_row['amount'] = floatval($row['amount']) + $package_row['amount'];
        $packages_row['number'] = intval($row['number']) + $package_row['number'];
        /* 格式化重量 */
        $packages_row['formated_weight'] = formated_weight($packages_row['weight']);
    
        return $packages_row;
    }
    
    /**
     * 取得支付方式信息
     * @param   int     $pay_id     支付方式id
     * @return  array   支付方式信息
     */
    public function payment_info($pay_id) {
        $sql = 'SELECT * FROM ' . C('DB_PREFIX') . "payment WHERE pay_id = '$pay_id' AND enabled = 1 limit 1";
       $Model=new Model();
       $row=$Model->query($sql);
        return $row[0];
    }
    
    /**
     * 检查订单中商品库存,以及上下架状态
     *
     * @access  public
     * @param   array   $arr
     *
     * @return  void
     */
   public function flow_cart_stock($arr,$user_id,$wid=0) {
       $Model=new Model(); 
       $goods_mod = D('goods');
       foreach ($arr AS $key => $val) {
            $val = intval(make_semiangle($val));
            if ($val <= 0 || !is_numeric($key)) {
                continue;
            }
            $map = array('rec_id'=>$key,'user_id'=>$user_id);
            $goods = D('cart')->where($map)->find();
            $row = $goods_mod->alias('g')->field('g.goods_name, g.goods_number, g.is_on_sale, c.product_id')->join('left join '.C('DB_PREFIX') . 'cart AS c on g.goods_id = c.goods_id')->where(array('c.rec_id'=>$key))->find();
            if($row['is_on_sale']!=1){
            	returnApiError('商品'.$row['goods_name'].'已下架');
            }
            $goods['is_presell']=(int)$goods['is_presell'];
            if($goods['is_presell']!=0){
                $goods['is_presell']=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid);
            }
			if($goods['is_presell']==1){
				//系统启用了库存，检查输入的商品数量是否有效
				if (intval(C('use_storage')) > 0 && $goods['extension_code'] != 'package_buy') {
    				       if ($row['goods_number'] < $val) {
    					        returnApiError('商品'.$row['goods_name'].'库存不足');
    					    }
    					    
    					    /* 是货品 */
    					    $row['product_id'] = trim($row['product_id']);
    					    if (!empty($row['product_id'])) {
    					        $product_number = D('products')->field('product_number')->where(array('goods_id'=>$goods['goods_id'],'product_id'=>$row['product_id']))->getField('product_number');
    					        if ($product_number < $val) {
    					            returnApiError('商品'.$row['goods_name'].'库存不足');
    					        }
    					    }
				} elseif (intval(C('use_storage')) > 0 && $goods['extension_code'] == 'package_buy') {
					if ($this->judge_package_stock($goods['goods_id'], $val)) {
						returnApiError('礼包内商品（'.$row['goods_name'].'）库存不足');
					}
				}
			}elseif($wid){
				if(!D('Goodsstorage')->check_warehous_goods($wid,$goods['goods_id'],$val)){
					returnApiError('仓库商品库存不足');
				}
			}
			
			//限购商品检查
			if($goods['is_quota']>0){
				$has_buy_number = $this->get_quota_goods_number($user_id, $goods['is_quota'], $goods['goods_id']);
				$quota_goods = $this->get_quota_goods_limit_num($goods['is_quota'], $goods['goods_id']);
				if(!empty($quota_goods)){
					if($quota_goods['count']<$has_buy_number+$goods['goods_number']){
						$rest_num = $has_buy_number+$goods['goods_number']-$quota_goods['count'];
						if($rest_num>0){
							returnApiError($goods['goods_name']."活动限购" . $quota_goods['count'] . "份，你只能再购买" . $rest_num . "份");
						}else{
							returnApiError($goods['goods_name']."活动限购" . $quota_goods['count'] . "份，您已购买了".$has_buy_number. "份");
						}
					}
				}
			}
			//分类限购检查
			$res = D('Goods')->check_cat_max_buy_number($goods,$goods['goods_price'],$user_id,$goods['goods_number']);
			
        }
    }
    
    
    
    /**
     * 获取限购商品已经购买的数量
     */
    public function get_quota_goods_number($uid,$act_id,$goods_id){
    	$map = array();
    	$map['user_id'] = $uid;
    	$map['act_id'] = $act_id;
    	$map['goods_id'] = $goods_id;
    	
    	$has_buy_number = M('activity_quota')->where($map)->count();
    	
    	return $has_buy_number;
    }
    
    /**
     * 获取限购活动商品配置
     * @param int $act_id
     */
    public function get_quota_goods_limit_num($act_id,$goods_id){
    	$activity = D ( 'favourable_activity' );
    	$favourable = $activity->favourable_info($act_id);
    	
 		foreach($favourable['quota'] as $key=>$val){
 			if($val['id']==$goods_id){
 				$activity_goods = $val;
 				break;
 			}
 		}
 		
 		return $activity_goods;
    }
    /**
     * 检查礼包内商品的库存
     * @return  boolen
     */
    public function judge_package_stock($package_id, $package_num = 1) {
        $sql = "SELECT goods_id, product_id, goods_number
            FROM " . C('DB_PREFIX') .
                "package_goods WHERE package_id = '" . $package_id . "'";
        $Model=new Model();
        $row = $Model->query($sql);
        if (empty($row)) {
            return true;
        }
    
        /* 分离货品与商品 */
        $goods = array('product_ids' => '', 'goods_ids' => '');
        foreach ($row as $key=>$value) {
            if ($value['product_id'] > 0) {
                $goods['product_ids'] .= ',' . $value['product_id'];
                continue;
            }
    
            $goods['goods_ids'] .= ',' . $value['goods_id'];
        }
    
        /* 检查货品库存 */
        if ($goods['product_ids'] != '') {
            $sql = "SELECT p.product_id
                FROM " . C('DB_PREFIX') . "products AS p, " . C('DB_PREFIX') . "package_goods AS pg
                    WHERE pg.product_id = p.product_id
                    AND pg.package_id = '$package_id'
                    AND pg.goods_number * $package_num > p.product_number
                    AND p.product_id IN (" . trim($goods['product_ids'], ',') . ")";
            $row = $Model->query($sql);
    
            if (!empty($row)) {
                return true;
            }
        }
    
        /* 检查商品库存 */
        if ($goods['goods_ids'] != '') {
            $sql = "SELECT g.goods_id
                FROM " . C('DB_PREFIX') . "goods AS g, " . C('DB_PREFIX') . "package_goods AS pg
                    WHERE pg.goods_id = g.goods_id
                    AND pg.goods_number * $package_num > g.goods_number
                    AND pg.package_id = '" . $package_id . "'
                AND pg.goods_id IN (" . trim($goods['goods_ids'], ',') . ")";
            $row = $Model->query($sql);
    
            if (!empty($row)) {
                return true;
            }
        }
    
        return false;
    }
    
    /**
     * 查询配送区域属于哪个办事处管辖
     * @param   array   $regions    配送区域（1、2、3、4级按顺序）
     * @return  int     办事处id，可能为0
     */
    public function get_agency_by_regions($regions) {
        if (!is_array($regions) || empty($regions)) {
            return 0;
        }
    
        $arr = array();
        $sql = "SELECT region_id, agency_id " .
            "FROM " . C('DB_PREFIX') .
            "region WHERE region_id " . db_create_in($regions) .
            " AND region_id > 0 AND agency_id > 0";
        $Model=new Model();
        $res = $Model->query($sql);
        foreach ($res as $key=>$row) {
            $arr[$row['region_id']] = $row['agency_id'];
        }
        if (empty($arr)) {
            return 0;
        }
    
        $agency_id = 0;
        for ($i = count($regions) - 1; $i >= 0; $i--) {
            if (isset($arr[$regions[$i]])) {
                return $arr[$regions[$i]];
            }
        }
    }
    
    /**
     * 过滤表字段
     * @param type $table
     * @param type $data
     * @return type
     */
    public function filter_field($table, $data) {
        $thistable = M($table);
        $field = $thistable->getDbFields();
        
        $res = array();
        foreach ($field as $field_name) {
            if (array_key_exists($field_name, $data)) {
                $res[$field_name] = $data[$field_name];
            }
        }
        return $res;
    }
    
    /**
     * 设置红包为已使用
     * @param   int     $bonus_id   红包id
     * @param   int     $order_id   订单id
     * @param	int	$pay_log_id	订单支付记录id 
     * @return  bool
     */
   public  function use_bonus($bonus_id, $order_id, $pay_log_id=0) {
        $sql = "UPDATE " . C('DB_PREFIX') .
        "user_bonus SET order_id = '$order_id', used_time = '" . gmtime() . "', pay_log_id = '".$pay_log_id."' " .
        "WHERE bonus_id = '$bonus_id' LIMIT 1";
        //dump($sql);
        $Model=new Model();
        return $Model->execute($sql);
    }
    
    
    /**
     * 改变订单中商品库存
     * @param   int     $order_id   订单号
     * @param   bool    $is_dec     是否减少库存
     * @param   bool    $storage     减库存的时机，1，下订单时；0，发货时；
     */
    public function change_order_goods_storage($order_id, $is_dec = true, $storage = 0,$wid=0) {
        /* 查询订单商品信息 */
        switch ($storage) {
            case 0 :
                $sql = "SELECT goods_id,goods_name,SUM(send_number) AS num, MAX(extension_code) AS extension_code, product_id,is_presell FROM " . C('DB_PREFIX') .
                "order_goods WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
                break;
    
            case 1 :
                $sql = "SELECT goods_id,goods_name,SUM(goods_number) AS num, MAX(extension_code) AS extension_code, product_id,is_presell FROM " . C('DB_PREFIX') .
                "order_goods WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
                break;
        }
        $Model=new Model();
        $res = $Model->query($sql);

        $check_storage = array('status'=>1,'msg'=>'ok','error_code'=>100);
        $goods_presell = array();
        foreach ($res as $key=>$row) {
        	//$goods['is_presell']=D('Goodsstorage')->check_whether_presell($row['goods_id'],$wid);
        	$goods_presell[$row['goods_id']] = $row['is_presell'];
        	if($row['is_presell']==1){
        		$goods_number = D('goods')->where(array('goods_id'=>$row['goods_id']))->getField('goods_number');
        		//系统启用了库存，检查输入的商品数量是否有效
        		if (intval(C('use_storage')) > 0 && $row['extension_code'] != 'package_buy') {
        			if ($goods_number < $row['num']) {
//         				returnApiError('商品'.$row['goods_name'].'库存不足');
        				$check_storage['status'] = 0;
        				$check_storage['msg'] = '商品'.$row['goods_name'].'库存不足';
                        $check_storage['error_code'] = 201;
        				return $check_storage;
        			}

        			/* 是货品 */
        			$row['product_id'] = trim($row['product_id']);
        			if (!empty($row['product_id'])) {
        				$product_number = D('products')->where(array('goods_id'=>$row['goods_id'],'product_id'=>$row['product_id']))->getField('product_number');
        				if ($product_number < $row['num']) {
//         					returnApiError('商品'.$row['goods_name'].'库存不足');
        					$check_storage['status'] = 0;
        					$check_storage['msg'] = '商品'.$row['goods_name'].'库存不足';
                            $check_storage['error_code'] = 201;
        					return $check_storage;
        				}
        			}
        		} elseif (intval(C('use_storage')) > 0 && $row['extension_code'] == 'package_buy') {
        			if ($this->judge_package_stock($row['goods_id'], $row['num'])) {
//         				returnApiError('礼包内商品（'.$row['goods_name'].'）库存不足');
        				$check_storage['status'] = 0;
        				$check_storage['msg'] = '礼包内商品（'.$row['goods_name'].'）库存不足';
                        $check_storage['error_code'] = 201;
        				return $check_storage;
        			}
        		}
        	}
        }
        foreach ($res as $key=>$row) {
        	//判断是否是预售商品，如果是，则减少虚拟库存，不是则跳过不处理
//         	$is_presell = D('Goodsstorage')->check_whether_presell($row['goods_id'],$wid);
			$is_presell = $goods_presell[$row['goods_id']];
        	if(!$is_presell){
        		continue;
        	}
            if ($row['extension_code'] != "package_buy") {
                if ($is_dec) {
                    $this->change_goods_storage($row['goods_id'], $row['product_id'], - $row['num']);
                } else {
                    $this->change_goods_storage($row['goods_id'], $row['product_id'], $row['num']);
                }
//                 $Model->query($sql);
            } else {
                $sql = "SELECT goods_id, goods_number" .
                    " FROM " . C('DB_PREFIX') .
                    "package_goods WHERE package_id = '" . $row['goods_id'] . "' limit 1";
                $row_goods = $Model->query($sql);
                $row_goods=$row_goods[0];
                $sql = "SELECT is_real" .
                    " FROM " . C('DB_PREFIX') .
                    "goods WHERE goods_id = '" . $row_goods['goods_id'] . "'";
                $is_goods = $Model->query($sql);
                $is_goods=$is_goods[0];
                if ($is_dec) {
                    $this->change_goods_storage($row_goods['goods_id'], $row['product_id'], - ($row['num'] * $row_goods['goods_number']));
                } elseif ($is_goods['is_real']) {
                    $this->change_goods_storage($row_goods['goods_id'], $row['product_id'], ($row['num'] * $row_goods['goods_number']));
                }
            }
        }
        
        return $check_storage;
    }
    
    /**
     * 商品库存增与减 货品库存增与减
     *
     * @param   int    $good_id         商品ID
     * @param   int    $product_id      货品ID
     * @param   int    $number          增减数量，默认0；
     *
     * @return  bool               true，成功；false，失败；
     */
    public function change_goods_storage($good_id, $product_id, $number = 0) {
        if ($number == 0) {
            return true; // 值为0即不做、增减操作，返回true
        }
    
        if (empty($good_id) || empty($number)) {
            return false;
        }
    
        $number = ($number > 0) ? '+ ' . $number : $number;
       
        /* 处理货品库存 */
        $products_query = true;
        $Model=new Model();
        if (!empty($product_id)) {
            $sql = "UPDATE " . C('DB_PREFIX')  .
            "products SET product_number = product_number $number
            WHERE goods_id = '$good_id'
            AND product_id = '$product_id'
            LIMIT 1";
           	try {
           		$products_query = $Model->execute($sql);
           	} catch (Exception $e) {
           		$products_query = false;
           	}
            
        }
    
        /* 处理商品库存 */
        $sql = "UPDATE " . C('DB_PREFIX') .
        "goods SET goods_number = goods_number $number
        WHERE goods_id = '$good_id'
        LIMIT 1";
		try {
			$query = $Model->execute($sql);
		} catch (Exception $e) {
			$query = false;
		}
        
        if ($query && $products_query) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 判断 购物车指定记录 是否存在
     * @param number $uid 用户ID； 
     * @param number $goods_id 商品ID；
     * @return boolean true存在；false不存在；
     * @author 43
     */
    public function is_exists_record( $uid, $goods_id,$act_id=0,$act_type="",$goods_attr_id=0) {
        $where["goods_id"] = $goods_id;
        $where["user_id"] = $uid;
       	$where["is_quota"] = 0; 
       	$where["is_gift"] = 0;
       	$where["can_handsel"] = 0;
       	$where["goods_attr_id"] = $goods_attr_id; 
        if(!empty($act_id) && !empty($act_type)){
        	$where[$act_type] = $act_id;
        }
        $info = $this->where($where)->find();
        
        if( !empty($info) ) {
            return $info;
        }else {
            return false;
        }
    }
    
    /**
     * 增减购物车商品数量
     * @param number $uid 用户ID；
     * @param number $goods_id 商品ID；
     * @param string $operate 操作类型：默认为增加add；删除del;
     * @param number $num 增减个数，默认为1；
     * @return array  is_ok：true成功；false失败；
     * @author 43
     */
    public function regulation_goods_num_4cart( $uid, $goods_id, $operate, $num,$act_id,$act_type,$goods_attr_id ) {
        $is_ok = false;
        
        $where["goods_id"] = $goods_id;
        $where["user_id"] = $uid;
        $where["is_quota"] = 0;
        $where["is_gift"] = 0;
        $where["can_handsel"] = 0;
        $where["is_quota"] = 0;
        $where["is_quota"] = 0;
        $where["goods_attr_id"] = $goods_attr_id;
        if(!empty($act_id) && !empty($act_type)){
        	$where[$act_type] = $act_id;
        }
        /// 增加数量
        if( $operate == "add" ) {
            $is_ok = $this->where($where)->setInc("goods_number", $num);

        /// 减少数量
        }else if( $operate == "dec" ) {
            $cur_num = $this->where($where)->getField("goods_number");

            if( $cur_num > $num ) {
                $is_ok = $this->where($where)->setDec("goods_number", $num);
            }else {
                $is_ok = $this->where($where)->delete();
            }            
        }else if( $operate == "del" ){
            $is_ok = $this->where($where)->delete();
        }
        
        /// 获取购物车 商品数据 商品总价(不含运费)
        $sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .
            ' FROM ' . C('DB_PREFIX') . 'cart ' .
            " WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "'";
        $Model=new Model();
        $row = $Model->query($sql);
        $row=$row[0];
        if ($row) {
            $number = intval($row['number']);
            $amount = floatval($row['amount']);
        } else {
            $number = 0;
            $amount = 0;
        }
        $cart_data["number"] = $number;
        $cart_data["amount"] = $amount;
        
        return array( "is_ok"=>$is_ok, "cart_data" => $cart_data );
    }
    
    
    public function buy_agian($order_goods_list){
    	$goodslist = array();
    	
    	foreach ($order_goods_list as $key=>$val){
    		$goods = array();
    		$goods = $this->convert_to_cart_data($val);
    		
    		$goodslist[] = $goods;
    	}
    }
    
    public function convert_to_cart_data($goods,$uid){
    	$data = array();
    	$data['user_id'] = $uid;
    	$data['session_id'] = SESS_ID;
    	$data['goods_id'] = $goods['goods_id'];
    	$data['goods_sn'] = $goods['goods_sn'];
    	$data['product_id'] = $goods['product_id'];
    	$data['goods_name'] = $goods['goods_name'];
    	$data['market_price'] = $goods['market_price'];
    	$data['goods_price'] = $goods['goods_price'];
    	$data['goods_number'] = $goods['goods_number'];
    	$data['goods_attr'] = $goods['goods_attr'];
    	$data['extension_code'] = $goods['extension_code'];
    	$data['parent_id'] = $goods['parent_id'];
    	$data['rec_type'] = 0;
    	$data['is_gift'] = $goods['is_gift'];
    	$data['is_quota'] = $goods['is_quota'];
    	$data['is_shipping'] =0;	
    	$data['can_handsel'] = 0;
    	$data['goods_attr_id'] = $goods['goods_attr_id'];
    	$data['is_presell'] = $goods['is_presell'];
    	
    	return $data;
    }
    
    
    public function get_goods_info($goods){
    	//检测商品
    	if($goods['is_quota']>0){
    		
    	}
    	$this->is_exists_record($uid, $goods_id);
    }
    
    public function check_quota_goods($goods_id,$act_id){
    	$activity = D ( 'favourable_activity' );
    	$cart = D('cart');
    	$favourable = $activity->favourable_info($act_id);
    	 
    	if (empty($favourable)) {
    		return false;
    	}
    	/* 判断活动类型 */
    	if ($favourable ['act_type'] <> 3) {
    		return false;
    	}
    	
    	/* 判断活动日期是否有效 */
    	$time = gmtime();
    	if ($time < $favourable['_start_time'] || $time > $favourable['_end_time']) {
    		return false;
    	}
    	
    	/* 判断用户能否享受该优惠 */
    	if (! $cart->favourable_available ( $favourable, $uid )) {
    		return false;
    	}
    	
    	/* 检查是否选择了产品 */
    	if (empty ( $goods_id )) {
    		return false;
    	}
    	
    	/* 检查产品是否有效 */
    	$quota_goods = array ();
    	foreach ( $favourable ['quota'] as $item ) {
    		if ($item ['id'] == $goods_id) {
    			$quota_goods = $item;
    			break;
    		}
    	}
    	
    	if (empty ( $quota_goods )) {
    		return false;
    	}
    }
    
}